title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Editing XML as a dictionary in python?
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('co...
8
2008-09-24T14:44:45Z
128,023
<p>For easy manipulation of XML in python, I like the <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> library. It works something like this:</p> <p>Sample XML File:</p> <pre><code>&lt;root&gt; &lt;level1&gt;leaf1&lt;/level1&gt; &lt;level2&gt;leaf2&lt;/level2&gt; &lt;/root...
8
2008-09-24T15:56:06Z
[ "python", "xml", "dictionary" ]
Editing XML as a dictionary in python?
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('co...
8
2008-09-24T14:44:45Z
2,303,733
<p>This'll get you a dict minus attributes... dunno if this is useful to anyone. I was looking for an xml to dict solution myself when i came up with this.</p> <pre><code> import xml.etree.ElementTree as etree tree = etree.parse('test.xml') root = tree.getroot() def xml_to_dict(el): d={} if el.text: d[el.ta...
18
2010-02-20T21:07:56Z
[ "python", "xml", "dictionary" ]
Editing XML as a dictionary in python?
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('co...
8
2008-09-24T14:44:45Z
2,545,294
<p>most direct way to me :</p> <pre><code>root = ET.parse(xh) data = root.getroot() xdic = {} if data &gt; None: for part in data.getchildren(): xdic[part.tag] = part.text </code></pre>
0
2010-03-30T12:57:33Z
[ "python", "xml", "dictionary" ]
Editing XML as a dictionary in python?
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('co...
8
2008-09-24T14:44:45Z
6,088,101
<p>My modification of Daniel's answer, to give a marginally neater dictionary:</p> <pre><code>def xml_to_dictionary(element): l = len(namespace) dictionary={} tag = element.tag[l:] if element.text: if (element.text == ' '): dictionary[tag] = {} else: dictionary[t...
4
2011-05-22T13:06:04Z
[ "python", "xml", "dictionary" ]
Editing XML as a dictionary in python?
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('co...
8
2008-09-24T14:44:45Z
9,815,265
<p>XML has a rich infoset, and it takes some special tricks to represent that in a Python dictionary. Elements are ordered, attributes are distinguished from element bodies, etc.</p> <p>One project to handle round-trips between XML and Python dictionaries, with some configuration options to handle the tradeoffs in di...
0
2012-03-22T01:31:08Z
[ "python", "xml", "dictionary" ]
Editing XML as a dictionary in python?
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('co...
8
2008-09-24T14:44:45Z
10,599,880
<p>Adding this line</p> <pre><code>d.update(('@' + k, v) for k, v in el.attrib.iteritems()) </code></pre> <p>in the <a href="http://stackoverflow.com/a/2303733/1395962">user247686's code</a> you can have node attributes too. </p> <p>Found it in this post <a href="http://stackoverflow.com/a/7684581/1395962">http://s...
1
2012-05-15T11:37:03Z
[ "python", "xml", "dictionary" ]
How to implement a Decorator with non-local equality?
127,736
<p>Greetings, currently I am refactoring one of my programs, and I found an interesting problem.</p> <p>I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no actio...
2
2008-09-24T15:08:50Z
128,005
<p>From the code that was posted, the only difference between Transition and Labeled Transition is the return of get_lable() and has_label(). In which case you can compress these two a single class that sets a label attribute to None and </p> <pre><code>return self.label is not None </code></pre> <p>in the has_label...
0
2008-09-24T15:52:11Z
[ "python", "design", "decorator", "multiple-inheritance" ]
How to implement a Decorator with non-local equality?
127,736
<p>Greetings, currently I am refactoring one of my programs, and I found an interesting problem.</p> <p>I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no actio...
2
2008-09-24T15:08:50Z
219,303
<p>I think its clear that nobody really understands your question. I would suggest putting it in context and making it shorter. As an example, here's one possible implementation of the state pattern in python, please study it to get an idea.</p> <pre><code>class State(object): def __init__(self, name): sel...
2
2008-10-20T17:53:19Z
[ "python", "design", "decorator", "multiple-inheritance" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
127,825
<p>What is the exact error you get? Is it like the following:</p> <pre><code>&gt;&gt;&gt; datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z") ValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z </code></pre> <p>If yes, you can split your ...
22
2008-09-24T15:19:27Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
127,872
<pre> import re,datetime s="2008-09-03T20:56:35.450686Z" d=datetime.datetime(*map(int, re.split('[^\d]', s)[:-1])) </pre>
35
2008-09-24T15:27:24Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
127,934
<p>Try the <a href="https://bitbucket.org/micktwomey/pyiso8601">iso8601</a> module; it does exactly this.</p> <p>There are several other options mentioned on the <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> page on the python.org wiki.</p>
46
2008-09-24T15:38:17Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
127,972
<p>Note in Python 2.6+ and Py3K, the %f character catches microseconds.</p> <pre><code>&gt;&gt;&gt; datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ") </code></pre> <p>See issue <a href="http://bugs.python.org/issue1158">here</a></p>
80
2008-09-24T15:45:02Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
6,772,287
<p>For something that works with the 2.X standard library try:</p> <pre><code>calendar.timegm(time.strptime(date.split(".")[0]+"UTC", "%Y-%m-%dT%H:%M:%S%Z")) </code></pre> <p>calendar.timegm is the missing gm version of time.mktime.</p>
2
2011-07-21T06:47:19Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
15,175,034
<p>I've coded up a parser for the ISO 8601 standard and put it on github: <a href="https://github.com/boxed/iso8601" rel="nofollow">https://github.com/boxed/iso8601</a> This implementation supports everything in the spec except for durations, intervals and periodic intervals and dates outside the supported date range o...
3
2013-03-02T13:31:49Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
15,228,038
<p>The <em>python-dateutil</em> package can parse not only RFC 3339 datetime strings like the one in the question, but also other ISO 8601 date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date).</p> <pre><code>&gt;&gt;&gt; import dateutil.parser &gt...
186
2013-03-05T15:44:16Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
18,150,817
<p>The python-dateutil will throw an exception if parsing invalid date strings, so you may want to catch the exception.</p> <pre><code>from dateutil import parser ds = '2012-60-31' try: dt = parser.parse(ds) except ValueError, e: print '"%s" is an invalid date' % ds </code></pre>
1
2013-08-09T15:53:22Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
22,700,869
<p>If you don't want to use dateutil, you can try this function:</p> <pre><code>def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"): """ Convert UTC time string to time.struct_time """ # change datetime.datetime to time, return time.struct_time type return datetime.datetime.strptime(utcTime, fmt) </c...
9
2014-03-27T22:50:16Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
28,528,461
<p>Nobody has mentioned it yet. In these days, <a href="http://arrow.readthedocs.org/">Arrow</a> also can be used as a third party solution.</p> <pre><code>&gt;&gt;&gt; import arrow &gt;&gt;&gt; date = arrow.get("2008-09-03T20:56:35.450686Z") &gt;&gt;&gt; date.datetime datetime.datetime(2008, 9, 3, 20, 56, 35, 450686,...
14
2015-02-15T16:47:44Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
28,979,667
<p>This works for stdlib on Python 3.2 onwards (edit: assuming all the timestamps are UTC):</p> <pre><code>from datetime import datetime, timezone, timedelta datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ").replace( tzinfo=timezone(timedelta(0))) </code></pre> <p>e.g.</p> <pre><code>&gt;&gt;&gt; datetime.ut...
1
2015-03-11T06:03:35Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
30,696,682
<p><a href="http://stackoverflow.com/a/127972/1709587">Several</a> <a href="http://stackoverflow.com/a/127825/1709587">answers</a> <a href="http://stackoverflow.com/a/22700869/1709587">here</a> <a href="http://stackoverflow.com/a/28979667/1709587">suggest</a> using <a href="https://docs.python.org/library/datetime.html...
45
2015-06-07T17:53:25Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
32,876,091
<p>If you are working with Django, it provides the <a href="https://docs.djangoproject.com/en/1.8/ref/utils/#module-django.utils.dateparse">dateparse module</a> that accepts a bunch of formats similar to ISO format, including the time zone.</p> <p>If you are not using Django and you don't want to use one of the other ...
5
2015-09-30T21:42:22Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
35,991,099
<p>Thanks to great <a href="http://stackoverflow.com/a/30696682/719457">Mark Amery's answer</a> I devised function to account for all possible ISO formats of datetime:</p> <pre><code>class FixedOffset(tzinfo): """Fixed offset in minutes: `time = utc_time + utc_offset`.""" def __init__(self, offset): se...
0
2016-03-14T15:05:53Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
38,848,051
<pre><code>def parseISO8601DateTime(datetimeStr): import time from datetime import datetime, timedelta def log_date_string(when): gmt = time.gmtime(when) if time.daylight and gmt[8]: tz = time.altzone else: tz = time.timezone if tz &gt; 0: ...
0
2016-08-09T10:17:22Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
39,150,189
<p>One straightforward way to convert an ISO 8601-like date string to a UNIX timestamp or <code>datetime.datetime</code> object in all supported Python versions without installing third-party modules is to use the <a href="https://www.sqlite.org/lang_datefunc.html" rel="nofollow">date parser of SQLite</a>.</p> <pre><c...
0
2016-08-25T16:16:26Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
How to parse an ISO 8601-formatted date in Python?
127,803
<p>I need to parse <a href="https://tools.ietf.org/html/rfc3339">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>strptime</code></a> in the Python ...
311
2008-09-24T15:17:00Z
39,387,583
<p>Django's <strong>parse_datetime</strong>() function supports dates with UTC offsets:</p> <pre><code>parse_datetime('2016-08-09T15:12:03.65478Z') = datetime.datetime(2016, 8, 9, 15, 12, 3, 654780, tzinfo=&lt;UTC&gt;) </code></pre> <p>So it could be used for parsing iso-8601 dates in fields within entire project:</p...
2
2016-09-08T09:42:18Z
[ "python", "parsing", "datetime", "iso8601", "rfc3339" ]
What is the best way to store set data in Python?
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from ...
4
2008-09-24T16:39:08Z
128,361
<p>Sets don't have keys. The element <strong>is</strong> the key.</p> <p>If you think you want keys, you have a mapping. More-or-less by definition.</p> <p>Sequential list lookup can be slow, even using a binary search. Mappings use hashes and are fast.</p> <p>Are you talking about a dictionary like this?</p> <p...
1
2008-09-24T16:59:10Z
[ "python", "dictionary", "data-structures", "set" ]
What is the best way to store set data in Python?
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from ...
4
2008-09-24T16:39:08Z
128,393
<p>How about using <code>{id: (description, id_type)}</code> dictionary? Or <code>{(id, id_type): description}</code> dictionary if (id,id_type) is the key.</p>
0
2008-09-24T17:04:11Z
[ "python", "dictionary", "data-structures", "set" ]
What is the best way to store set data in Python?
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from ...
4
2008-09-24T16:39:08Z
128,526
<p>Sets in Python are implemented using hash tables. In earlier versions, they were actually implemented using sets, but that has changed AFAIK. The only thing you save by using a set would then be the size of a pointer for each entry (the pointer to the value). </p> <p>To use only a part of a tuple for the hashcode, ...
0
2008-09-24T17:30:36Z
[ "python", "dictionary", "data-structures", "set" ]
What is the best way to store set data in Python?
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from ...
4
2008-09-24T16:39:08Z
128,550
<p>I'm assuming the problem you try to solve by cutting down on the memory you use is the address space limit of your process. Additionally you search for a data structure that allows you fast insertion and reasonable sequential read out.</p> <h2>Use less structures except strings (str)</h2> <p>The question you ask i...
1
2008-09-24T17:32:59Z
[ "python", "dictionary", "data-structures", "set" ]
What is the best way to store set data in Python?
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from ...
4
2008-09-24T16:39:08Z
128,565
<p>It's still murky, but it sounds like you have some several lists of [(id, description, type)...]</p> <p>The id's are unique within a list and consistent between lists.</p> <p>You want to create a UNION: a single list, where each id occurs once, with possibly multiple descriptions.</p> <p>For some reason, you thin...
0
2008-09-24T17:36:20Z
[ "python", "dictionary", "data-structures", "set" ]
What is the best way to store set data in Python?
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from ...
4
2008-09-24T16:39:08Z
129,396
<p>If you're doing an n-way merge with removing duplicates, the following may be what you're looking for.</p> <p>This generator will merge any number of sources. Each source must be a sequence. The key must be in position 0. It yields the merged sequence one item at a time.</p> <pre><code>def merge( *sources ): ...
1
2008-09-24T19:40:55Z
[ "python", "dictionary", "data-structures", "set" ]
What's the best way to upgrade from Django 0.96 to 1.0?
128,466
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
7
2008-09-24T17:19:38Z
128,483
<p>Upgrade. For me it was very simple: change <code>__str__()</code> to <code>__unicode__()</code>, write basic <code>admin.py</code>, and done. Just start running your app on 1.0, test it, and when you encounter an error use the documentation on <a href="http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges"...
3
2008-09-24T17:23:18Z
[ "python", "django" ]
What's the best way to upgrade from Django 0.96 to 1.0?
128,466
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
7
2008-09-24T17:19:38Z
128,496
<p>Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that breaks. In my experience, the main things that I've had to fix after an upgrade are</p> <ol> <li><p>Changes to some of the funky stuff with models, such as the syntax for following foreign keys...
5
2008-09-24T17:26:05Z
[ "python", "django" ]
What's the best way to upgrade from Django 0.96 to 1.0?
128,466
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
7
2008-09-24T17:19:38Z
129,187
<p>Just upgrade your app. The switch from 0.96 to 1.0 was huge, but in terms of Backwards Incompatible changes I doubt your app even has 10% of them.</p> <p>I was on trunk before Django 1.0 so I the transition for me was over time but even then the only major things I had to change were newforms, newforms-admin, <stro...
2
2008-09-24T19:08:01Z
[ "python", "django" ]
What's the best way to upgrade from Django 0.96 to 1.0?
128,466
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
7
2008-09-24T17:19:38Z
138,666
<p>Only simplest sites are easy to upgrade.</p> <p>Expect real pain if your site happen to be for <em>non-ASCII</em> part of the world (read: anywhere outside USA and UK). The most painful change in Django was switching from bytestrings to unicode objects internally - now you have to find all places where you use byte...
1
2008-09-26T10:40:03Z
[ "python", "django" ]
What's the best way to upgrade from Django 0.96 to 1.0?
128,466
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
7
2008-09-24T17:19:38Z
410,942
<p>We upgraded in a multi step process and I'm quite happy with that. The application in Question was about 100.000 LoC and running several core business functions with lot's of interfacing to legacy systems. We worked like that:</p> <ol> <li>Update to django 0.97-post unicode merge. Fix all the unicode issues</li> <l...
1
2009-01-04T12:52:44Z
[ "python", "django" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,522
<p>The first variant is indeed more efficient than the second when the function is called either zero or one times. With the second and subsequent invocations, however, the "import every call" approach is actually less efficient. See <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips#head-c849d5d5d94bc3...
11
2008-09-24T17:30:04Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,525
<p>I wouldn't worry about the efficiency of loading the module up front too much. The memory taken up by the module won't be very big (assuming it's modular enough) and the startup cost will be negligible.</p> <p>In most cases you want to load the modules at the top of the source file. For somebody reading your code...
3
2008-09-24T17:30:34Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,532
<p>Most of the time this would be useful for clarity and sensible to do but it's not always the case. Below are a couple of examples of circumstances where module imports might live elsewhere.</p> <p>Firstly, you could have a module with a unit test of the form:</p> <pre><code>if __name__ == '__main__': import f...
21
2008-09-24T17:31:08Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,534
<p>It's a tradeoff, that only the programmer can decide to make. </p> <p>Case 1 saves some memory and startup time by not importing the datetime module (and doing whatever initialization it might require) until needed. Note that doing the import 'only when called' also means doing it 'every time when called', so each...
4
2008-09-24T17:31:17Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,549
<p>Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.</p> <p>Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.</p> <p>If you have to load heavyweight modules at unexpec...
6
2008-09-24T17:32:50Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,577
<p>Module importing is quite fast, but not instant. This means that:</p> <ul> <li>Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once.</li> <li>Putting the imports within a function will cause calls to that function to take longer.</li> </ul> <p>So if you care about...
141
2008-09-24T17:38:00Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,641
<p>Here's an example where all the imports are at the very top (this is the only time I've needed to do this). I want to be able to terminate a subprocess on both Un*x and Windows.</p> <pre><code>import os # ... try: kill = os.kill # will raise AttributeError on Windows from signal import SIGTERM def ter...
4
2008-09-24T17:48:02Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,655
<p>This is like many other optimizations - you sacrifice some readability for speed. As John mentioned, if you've done your profiling homework and found this to be a significantly useful enough change <strong>and</strong> you need the extra speed, then go for it. It'd probably be good to put a note up with all the ot...
3
2008-09-24T17:49:54Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,684
<p>Module initialization only occurs once - on the first import. If the module in question is from the standard library, then you will likely import it from other modules in your program as well. For a module as prevalent as datetime, it is also likely a dependency for a slew of other standard libraries. The import ...
2
2008-09-24T17:52:54Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
128,859
<p>I have adopted the practice of putting all imports in the functions that use them, rather than at the top of the module.</p> <p>The benefit I get is the ability to refactor more reliably. When I move a function from one module to another, I know that the function will continue to work with all of its legacy of test...
31
2008-09-24T18:16:13Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
129,810
<p>Putting the import statement inside of a function can prevent circular dependencies.</p>
46
2008-09-24T20:36:46Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
17,407,169
<p>Just to complete <a href="http://stackoverflow.com/a/129810/955619">Moe's answer</a> and the original question:</p> <p><strong>When we have to deal with circular dependences we can do some "tricks".</strong> Assuming we're working with modules <code>a.py</code> and <code>b.py</code> that contain <code>x()</code> an...
1
2013-07-01T14:41:01Z
[ "python", "optimization", "coding-style" ]
Should Python import statements always be at the top of a module?
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 08</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only us...
202
2008-09-24T17:21:47Z
36,406,101
<p>In addition to the excellent answers already given, it's worth noting that the placement of imports is not merely a matter of style. Sometimes a module has implicit dependencies that need to be imported or initialized first, and a top-level import could lead to violations of the required order of execution. </p> <p...
1
2016-04-04T14:56:03Z
[ "python", "optimization", "coding-style" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
128,624
<p>Here's my suggestion. Don't use class methods. </p> <p>Seriously. </p> <p>What's the reason for using class methods in this case? Why not have an ordinary object of an ordinary class?</p> <p><hr /></p> <p>If you simply want to change the value, a property isn't really very helpful is it? Just set the attrib...
-1
2008-09-24T17:45:17Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
128,812
<p>Half a solution, __set__ on the class does not work, still. The solution is a custom property class implementing both a property and a staticmethod</p> <pre><code>class ClassProperty(object): def __init__(self, fget, fset): self.fget = fget self.fset = fset def __get__(self, instance, owner...
2
2008-09-24T18:08:52Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
129,819
<p>There is no reasonable way to make this "class property" system to work in Python.</p> <p>Here is one unreasonable way to make it work. You can certainly make it more seamless with increasing amounts of metaclass magic.</p> <pre><code>class ClassProperty(object): def __init__(self, getter, setter): sel...
12
2008-09-24T20:38:47Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
129,868
<blockquote> <p>Because I need to modify an attribute that in such a way that is seen by all instances of a class, and in the scope from which these class methods are called does not have references to all instances of the class.</p> </blockquote> <p>Do you have access to at least one instance of the class? I can th...
3
2008-09-24T20:47:07Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
130,090
<p>Give this a try, it gets the job done without having to change/add a lot of existing code.</p> <pre><code>&gt;&gt;&gt; class foo(object): ... _var = 5 ... def getvar(cls): ... return cls._var ... getvar = classmethod(getvar) ... def setvar(cls, value): ... cls._var = value ... se...
1
2008-09-24T21:28:15Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
1,383,402
<p>Reading the <a href="http://www.python.org/download/releases/2.2/descrintro/#property">Python 2.2 release</a> notes, I find the following.</p> <blockquote> <p>The get method [of a property] won't be called when the property is accessed as a class attribute (C.x) instead of as an instance attribute (C().x). ...
64
2009-09-05T14:12:14Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
1,800,999
<p>A property is created on a class but affects an instance. So if you want a classmethod property, create the property on the metaclass.</p> <pre><code>&gt;&gt;&gt; class foo(object): _var = 5 class __metaclass__(type): pass @classmethod def getvar(cls): return cls._var @classmethod ...
48
2009-11-26T00:58:17Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
2,544,313
<p>Setting it only on the meta class doesn't help if you want to access the class property via an instantiated object, in this case you need to install a normal property on the object as well (which dispatches to the class property). I think the following is a bit more clear:</p> <pre><code>#!/usr/bin/python class cl...
6
2010-03-30T10:07:36Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
13,624,858
<p>I hope this dead-simple read-only <code>@classproperty</code> decorator would help somebody looking for classproperties.</p> <pre><code>class classproperty(object): def __init__(self, fget): self.fget = fget def __get__(self, owner_self, owner_cls): return self.fget(owner_cls) class C(obj...
20
2012-11-29T11:32:12Z
[ "python", "oop" ]
Using property() on classmethods
128,573
<p>I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>&gt;&gt;&gt...
104
2008-09-24T17:37:11Z
39,542,816
<blockquote> <h1>Is it possible to use the property() function with classmethod decorated functions?</h1> </blockquote> <p>No. </p> <p>However, a classmethod is simply a bound method (a partial function) on a class accessible from instances of that class.</p> <p>Since the instance is a function of the class and yo...
1
2016-09-17T04:21:19Z
[ "python", "oop" ]
Doing CRUD in Turbogears
128,689
<p>Are there any good packages or methods for doing extensive CRUD (create-retrieve-update-delete) interfaces in the Turbogears framework. The FastDataGrid widget is too much of a black box to be useful and CRUDTemplate looks like more trouble than rolling my own. Ideas? Suggestions?</p>
3
2008-09-24T17:53:29Z
142,712
<p>While <a href="http://docs.turbogears.org/1.0/CRUDTemplate" rel="nofollow">CRUDTemplate</a> looks mildly complex, I'd say that you can implement CRUD/ABCD using just about any ORM that you choose. It just depends on how much of it you with to automate (which generally means defining models/schemas ahead of time). Yo...
0
2008-09-27T01:30:15Z
[ "python", "crud", "turbogears" ]
Doing CRUD in Turbogears
128,689
<p>Are there any good packages or methods for doing extensive CRUD (create-retrieve-update-delete) interfaces in the Turbogears framework. The FastDataGrid widget is too much of a black box to be useful and CRUDTemplate looks like more trouble than rolling my own. Ideas? Suggestions?</p>
3
2008-09-24T17:53:29Z
158,626
<p>After doing some more digging and hacking it turns out to not be terribly hard to drop the Cakewalk interface into an application. It's not pretty without a lot of work, but it works right away.</p>
0
2008-10-01T16:56:35Z
[ "python", "crud", "turbogears" ]
Doing CRUD in Turbogears
128,689
<p>Are there any good packages or methods for doing extensive CRUD (create-retrieve-update-delete) interfaces in the Turbogears framework. The FastDataGrid widget is too much of a black box to be useful and CRUDTemplate looks like more trouble than rolling my own. Ideas? Suggestions?</p>
3
2008-09-24T17:53:29Z
1,282,180
<p>You should really take a look at sprox ( <a href="http://sprox.org/" rel="nofollow">http://sprox.org/</a> ).</p> <p>It builds on RESTController, is very straight forward, well documented (imo), generates forms and validation "magically" from your database and leaves you with a minimum of code to write. I really enj...
3
2009-08-15T15:50:29Z
[ "python", "crud", "turbogears" ]
Doing CRUD in Turbogears
128,689
<p>Are there any good packages or methods for doing extensive CRUD (create-retrieve-update-delete) interfaces in the Turbogears framework. The FastDataGrid widget is too much of a black box to be useful and CRUDTemplate looks like more trouble than rolling my own. Ideas? Suggestions?</p>
3
2008-09-24T17:53:29Z
1,508,044
<p>So you need CRUD. The best way to accomplish this is with a tool that takes all the lame code away. This tool is called <a href="http://www.turbogears.org/2.0/docs/main/Extensions/Admin/index.html" rel="nofollow">tgext.admin</a>. However you can use it at several levels.</p> <ul> <li><a href="http://pypi.python.org...
2
2009-10-02T06:47:32Z
[ "python", "crud", "turbogears" ]
Does Django support multi-value cookies?
128,815
<p>I'd like to set a cookie via Django with that has several different values to it, similar to .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie_members(VS.80).aspx" rel="nofollow">HttpCookie.Values</a> property. Looking at the <a href="http://docs.djangoproject.com/en/dev/ref/request-respo...
1
2008-09-24T18:09:14Z
128,957
<p>.NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem.</p> <p>I will say that you're doing the right thing, in not...
5
2008-09-24T18:35:11Z
[ "python", "django", "cookies" ]
Does Django support multi-value cookies?
128,815
<p>I'd like to set a cookie via Django with that has several different values to it, similar to .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie_members(VS.80).aspx" rel="nofollow">HttpCookie.Values</a> property. Looking at the <a href="http://docs.djangoproject.com/en/dev/ref/request-respo...
1
2008-09-24T18:09:14Z
129,964
<p>Django does not support it. The best way would be to separate the values with arbitrary separator and then just split the string, like you already said.</p>
0
2008-09-24T21:03:05Z
[ "python", "django", "cookies" ]
Does Django support multi-value cookies?
128,815
<p>I'd like to set a cookie via Django with that has several different values to it, similar to .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie_members(VS.80).aspx" rel="nofollow">HttpCookie.Values</a> property. Looking at the <a href="http://docs.djangoproject.com/en/dev/ref/request-respo...
1
2008-09-24T18:09:14Z
131,047
<p>If you're looking for something a little more abstracted, try using <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#examples" rel="nofollow">sessions</a>. I believe the way they work is by storing an id in the cookie that matches a database record. You can store whatever you want in it. It's not ...
1
2008-09-25T01:44:18Z
[ "python", "django", "cookies" ]
Does Django support multi-value cookies?
128,815
<p>I'd like to set a cookie via Django with that has several different values to it, similar to .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie_members(VS.80).aspx" rel="nofollow">HttpCookie.Values</a> property. Looking at the <a href="http://docs.djangoproject.com/en/dev/ref/request-respo...
1
2008-09-24T18:09:14Z
2,383,482
<p><strong>(Late answer!)</strong> </p> <p>This will be bulkier, but you call always use python's built in serializing.</p> <p>You could always do something like:</p> <pre><code>import pickle class MultiCookie(): def __init__(self,cookie=None,values=None): if cookie != None: try: ...
1
2010-03-04T23:24:10Z
[ "python", "django", "cookies" ]
Perl or Python script to remove user from group
128,933
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears th...
3
2008-09-24T18:30:36Z
129,012
<p>It looks like <em>deluser --group [groupname]</em> should do it.</p> <p>If not, the <em>groups</em> command lists the groups that a user belongs to. It should be fairly straightforward to come up with some Perl to capture that list into an array (or <em>map</em> it into a hash), delete the unwanted group(s), and f...
1
2008-09-24T18:42:35Z
[ "python", "perl", "sysadmin", "centos", "redhat" ]
Perl or Python script to remove user from group
128,933
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears th...
3
2008-09-24T18:30:36Z
129,245
<p>I found <a href="http://search.cpan.org/~ssnodgra/Unix-ConfigFile-0.06/GroupFile.pm" rel="nofollow">This</a> for you. It should do what you need. As far as I can tell Perl does not have any built in functions for removing users from a group. It has several for seeing the group id of a user or process.</p>
2
2008-09-24T19:15:32Z
[ "python", "perl", "sysadmin", "centos", "redhat" ]
Perl or Python script to remove user from group
128,933
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears th...
3
2008-09-24T18:30:36Z
129,468
<p>Here's a very simple little Perl script that should give you the list of groups you need:</p> <pre><code>my $user = 'user'; my $groupNoMore = 'somegroup'; my $groups = join ',', grep { $_ ne $groupNoMore } split /\s/, `groups $user`; </code></pre> <p>Getting and sanitizing the required arguments is left as an exec...
1
2008-09-24T19:54:07Z
[ "python", "perl", "sysadmin", "centos", "redhat" ]
Perl or Python script to remove user from group
128,933
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears th...
3
2008-09-24T18:30:36Z
462,545
<p>Web Link: <a href="http://www.ibm.com/developerworks/linux/library/l-roadmap4/" rel="nofollow">http://www.ibm.com/developerworks/linux/library/l-roadmap4/</a></p> <p>To add members to the group, use the gpasswd command with the -a switch and the user id you wish to add:</p> <p>gpasswd -a userid mygroup</p> <p>Re...
2
2009-01-20T18:42:40Z
[ "python", "perl", "sysadmin", "centos", "redhat" ]
Generic Exception Handling in Python the "Right Way"
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> ...
21
2008-09-24T19:00:47Z
129,172
<p>If they're simple one-line commands, you can wrap them in <code>lambda</code>s:</p> <pre><code>for cmd in [ (lambda: foo (a, b)), (lambda: bar (c, d)), ]: try: cmd () except StandardError, e: baz (e) </code></pre> <p>You could wrap that whole thing up in a function, so it looked lik...
4
2008-09-24T19:04:59Z
[ "python", "exception", "readability" ]
Generic Exception Handling in Python the "Right Way"
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> ...
21
2008-09-24T19:00:47Z
129,174
<p>The best approach I have found, is to define a function like such:</p> <pre><code>def handle_exception(function, reaction, *args, **kwargs): try: result = function(*args, **kwargs) except Exception, e: result = reaction(e) return result </code></pre> <p>But that just doesn't feel or loo...
2
2008-09-24T19:05:17Z
[ "python", "exception", "readability" ]
Generic Exception Handling in Python the "Right Way"
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> ...
21
2008-09-24T19:00:47Z
129,176
<p>In your specific case, you can do this:</p> <pre><code>try: foo(a, b) bar(c, d) except Exception, e: baz(e) </code></pre> <p>Or, you can catch the exception one step above:</p> <pre><code>try: foo_bar() # This function can throw at several places except Exception, e: baz(e) </code></pre>
-3
2008-09-24T19:05:48Z
[ "python", "exception", "readability" ]
Generic Exception Handling in Python the "Right Way"
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> ...
21
2008-09-24T19:00:47Z
129,177
<p>You could use the <a href="http://docs.python.org/whatsnew/pep-343.html"><code>with</code> statement</a> if you have python 2.5</p> <pre><code>from __future__ import with_statement import contextlib @contextlib.contextmanager def handler(): try: yield except Exception, e: baz(e) </code></pr...
57
2008-09-24T19:05:58Z
[ "python", "exception", "readability" ]
Generic Exception Handling in Python the "Right Way"
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> ...
21
2008-09-24T19:00:47Z
129,626
<p>You could try something like this. This is vaguely C macro-like.</p> <pre><code>class TryOrBaz( object ): def __init__( self, that ): self.that= that def __call__( self, *args ): try: return self.that( *args ) except Exception, e: baz( e ) TryOrBaz( foo )( a...
2
2008-09-24T20:15:09Z
[ "python", "exception", "readability" ]
Generic Exception Handling in Python the "Right Way"
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> ...
21
2008-09-24T19:00:47Z
133,336
<p>If this is always, <em>always</em> the behaviour you want when a particular function raises an exception, you could use a decorator:</p> <pre><code>def handle_exception(handler): def decorate(func): def call_function(*args, **kwargs): try: func(*args, **kwargs) ex...
9
2008-09-25T13:31:32Z
[ "python", "exception", "readability" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
129,518
<p>Have a look at the <a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> method of the <code>unittest</code> module.</p>
5
2008-09-24T20:01:43Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
129,522
<p>Use <a href="http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises"><code>TestCase.assertRaises</code></a> (or <code>TestCase.failUnlessRaises</code>) from the unittest module, for example:</p> <pre><code>import mymod class MyTestCase(unittest.TestCase): def test1(self): self.asse...
253
2008-09-24T20:02:29Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
129,528
<p>Your code should follow this pattern (this is a unittest module style test):</p> <pre><code>def test_afunction_throws_exception(self): try: afunction() except ExpectedException: pass except Exception as e: self.fail('Unexpected exception raised:', e) else: self.fail('Ex...
19
2008-09-24T20:03:24Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
129,610
<p>The code in my previous answer can be simplified to:</p> <pre><code>def test_afunction_throws_exception(self): self.assertRaises(ExpectedException, afunction) </code></pre> <p>And if afunction takes arguments, just pass them into assertRaises like this:</p> <pre><code>def test_afunction_throws_exception(self)...
120
2008-09-24T20:13:08Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
132,682
<p>I use <strong>doctest</strong>[1] almost everywhere because I like the fact that I document and test my functions at the same time.</p> <p>Have a look at this code:</p> <pre><code>def throw_up(something, gowrong=False): """ &gt;&gt;&gt; throw_up('Fish n Chips') Traceback (most recent call last): .....
7
2008-09-25T11:17:18Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
241,809
<p>I just discovered that the <a href="http://www.voidspace.org.uk/python/mock.html" rel="nofollow">Mock library</a> provides an assertRaisesWithMessage() method (in its unittest.TestCase subclass), which will check not only that the expected exception is raised, but also that it is raised with the expected message:</p...
4
2008-10-28T00:13:39Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
3,166,985
<p>Since Python 2.7 you can use context manager to get a hold of the actual Exception object thrown:</p> <pre><code>import unittest def broken_function(): raise Exception('This is broken') class MyTestCase(unittest.TestCase): def test(self): with self.assertRaises(Exception) as context: b...
129
2010-07-02T15:16:00Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
3,983,323
<p>You can use assertRaises from the unittest module</p> <pre><code>import unittest class TestClass(): def raises_exception(self): raise Exception("test") class MyTestCase(unittest.TestCase): def test_if_method_raises_correct_exception(self): test_class = TestClass() # note that you dont use () when ...
-1
2010-10-21T00:12:46Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
14,712,903
<p>from: <a href="http://www.lengrand.fr/2011/12/pythonunittest-assertraises-raises-error/">http://www.lengrand.fr/2011/12/pythonunittest-assertraises-raises-error/</a></p> <p>First, here is the corresponding (still dum :p) function in file dum_function.py :</p> <pre><code>def square_value(a): """ Returns the s...
5
2013-02-05T17:04:37Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
23,780,046
<p>You can build your own <code>contextmanager</code> to check if the exception was raised.</p> <pre><code>import contextlib @contextlib.contextmanager def raises(exception): try: yield except exception as e: assert True else: assert False </code></pre> <p>And then you can use <c...
1
2014-05-21T10:06:34Z
[ "python", "unit-testing", "exception", "exception-handling" ]
How do you test that a Python function throws an exception?
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
285
2008-09-24T20:00:35Z
28,223,420
<blockquote> <p><strong>How do you test that a Python function throws an exception?</strong></p> <p>How does one write a test that fails only if a function doesn't throw an expected exception?</p> </blockquote> <h1>Short Answer:</h1> <p>Use the <code>self.assertRaises</code> method as a context manager:</p> ...
48
2015-01-29T19:54:26Z
[ "python", "unit-testing", "exception", "exception-handling" ]
Getting Python to use the ActiveTcl libraries
129,912
<p>Is there any way to get Python to use my ActiveTcl installation instead of having to copy the ActiveTcl libraries into the Python/tcl directory?</p>
0
2008-09-24T20:54:21Z
130,179
<p>Not familiar with ActiveTcl, but in general here is how to get a package/module to be loaded when that name already exists in the standard library:</p> <pre><code>import sys dir_name="/usr/lib/mydir" sys.path.insert(0,dir_name) </code></pre> <p>Substitute the value for dir_name with the path to the directory conta...
2
2008-09-24T21:48:23Z
[ "python", "activetcl" ]
Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?
130,074
<p>python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:</p> <pre><code>time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float ...
17
2008-09-24T21:24:04Z
130,134
<p>I always thought the time and datetime modules were a little incoherent. Anyways, here's the inverse of mktime</p> <pre><code>import time def mkgmtime(t): """Convert UTC tuple to seconds since Epoch""" return time.mktime(t)-time.timezone </code></pre>
3
2008-09-24T21:38:28Z
[ "python" ]
Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?
130,074
<p>python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:</p> <pre><code>time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float ...
17
2008-09-24T21:24:04Z
130,138
<p>I'm only a newbie to Python, but here's my approach.</p> <pre><code>def mkgmtime(fields): now = int(time.time()) gmt = list(time.gmtime(now)) gmt[8] = time.localtime(now).tm_isdst disp = now - time.mktime(tuple(gmt)) return disp + time.mktime(fields) </code></pre> <p>There, my proposed name for...
0
2008-09-24T21:38:59Z
[ "python" ]
Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?
130,074
<p>python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:</p> <pre><code>time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float ...
17
2008-09-24T21:24:04Z
161,385
<p>There is actually an inverse function, but for some bizarre reason, it's in the <a href="https://docs.python.org/2/library/calendar.html" rel="nofollow">calendar</a> module: calendar.timegm(). I listed the functions in this <a href="http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-pyth...
27
2008-10-02T08:42:45Z
[ "python" ]
Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?
130,074
<p>python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:</p> <pre><code>time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float ...
17
2008-09-24T21:24:04Z
18,783,518
<p>mktime documentation is a bit misleading here, there is no meaning saying it's calculated as a local time, rather it's calculating the seconds from Epoch according to the supplied tuple - regardless of your computer locality.</p> <p>If you do want to do a conversion from a utc_tuple to local time you can do the fol...
0
2013-09-13T10:01:12Z
[ "python" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
130,276
<p>Came up with my own answer after a minute of thought. It can be done with nested comprehensions:</p> <pre><code>result = [y for y in (expensive(x) for x in mylist) if y] </code></pre> <p>I guess that works, though I find nested comprehensions are only marginally readable </p>
17
2008-09-24T22:12:24Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
130,278
<pre><code>result = [x for x in map(expensive,mylist) if x] </code></pre> <p>map() will return a list of the values of each object in mylist passed to expensive(). Then you can list-comprehend that, and discard unnecessary values.</p> <p>This is somewhat like a nested comprehension, but should be faster (since the py...
6
2008-09-24T22:12:26Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
130,285
<p>You could always <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoize</a> the <code>expensive()</code> function so that calling it the second time around is merely a lookup for the computed value of <code>x</code>.</p> <p><a href="http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08...
2
2008-09-24T22:14:18Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
130,288
<p>You could memoize expensive(x) (and if you are calling expensive(x) frequently, you probably should memoize it any way. This page gives an implementation of memoize for python:</p> <p><a href="http://code.activestate.com/recipes/52201/" rel="nofollow">http://code.activestate.com/recipes/52201/</a></p> <p>This has...
2
2008-09-24T22:15:58Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
130,309
<p>If the calculations are already nicely bundled into functions, how about using <code>filter</code> and <code>map</code>?</p> <pre><code>result = filter (None, map (expensive, mylist)) </code></pre> <p>You can use <code>itertools.imap</code> if the list is very large.</p>
17
2008-09-24T22:23:50Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
130,312
<p>The most obvious (and I would argue most readable) answer is to not use a list comprehension or generator expression, but rather a real generator:</p> <pre><code>def gen_expensive(mylist): for item in mylist: result = expensive(item) if result: yield result </code></pre> <p>It takes...
7
2008-09-24T22:24:42Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you ...
16
2008-09-24T22:08:57Z
133,898
<p>This is exactly what generators are suited to handle:</p> <pre><code>result = (expensive(x) for x in mylist) result = (do_something(x) for x in result if some_condition(x)) ... result = [x for x in result if x] # finally, a list </code></pre> <ol> <li>This makes it totally clear what is happening during each stag...
4
2008-09-25T15:12:20Z
[ "python", "list-comprehension" ]