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
sequence |
---|---|---|---|---|---|---|---|---|---|
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('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 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><root>
<level1>leaf1</level1>
<level2>leaf2</level2>
</root>
</code></pre>
<p>Python code:</p>
<pre><code>from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString
soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
soup.contents[0].name
# u'root'
</code></pre>
<p>You can use the node names as methods:</p>
<pre><code>soup.root.contents[0].name
# u'level1'
</code></pre>
<p>It is also possible to use regexes:</p>
<pre><code>import re
tags_starting_with_level = soup.findAll(re.compile('^level'))
for tag in tags_starting_with_level: print tag.name
# level1
# level2
</code></pre>
<p>Adding and inserting new nodes is pretty straightforward:</p>
<pre><code># build and insert a new level with a new leaf
level3 = Tag(soup, 'level3')
level3.insert(0, NavigableString('leaf3')
soup.root.insert(2, level3)
print soup.prettify()
# <root>
# <level1>
# leaf1
# </level1>
# <level2>
# leaf2
# </level2>
# <level3>
# leaf3
# </level3>
# </root>
</code></pre>
| 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('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 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.tag] = el.text
else:
d[el.tag] = {}
children = el.getchildren()
if children:
d[el.tag] = map(xml_to_dict, children)
return d
</code></pre>
<p>This: <a href="http://www.w3schools.com/XML/note.xml" rel="nofollow">http://www.w3schools.com/XML/note.xml</a></p>
<pre><code><note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</code></pre>
<p>Would equal this:</p>
<pre><code>
{'note': [{'to': 'Tove'},
{'from': 'Jani'},
{'heading': 'Reminder'},
{'body': "Don't forget me this weekend!"}]}
</code></pre>
| 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('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 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 > 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('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 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[tag] = element.text
children = element.getchildren()
if children:
subdictionary = {}
for child in children:
for k,v in xml_to_dictionary(child).items():
if k in subdictionary:
if ( isinstance(subdictionary[k], list)):
subdictionary[k].append(v)
else:
subdictionary[k] = [subdictionary[k], v]
else:
subdictionary[k] = v
if (dictionary[tag] == {}):
dictionary[tag] = subdictionary
else:
dictionary[tag] = [dictionary[tag], subdictionary]
if element.attrib:
attribs = {}
for k,v in element.attrib.items():
attribs[k] = v
if (dictionary[tag] == {}):
dictionary[tag] = attribs
else:
dictionary[tag] = [dictionary[tag], attribs]
return dictionary
</code></pre>
<p>namespace is the xmlns string, including braces, that ElementTree prepends to all tags, so here I've cleared it as there is one namespace for the entire document</p>
<p>NB that I adjusted the raw xml too, so that 'empty' tags would produce at most a ' ' text property in the ElementTree representation</p>
<pre><code>spacepattern = re.compile(r'\s+')
mydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))
</code></pre>
<p>would give for instance</p>
<pre><code>{'note': {'to': 'Tove',
'from': 'Jani',
'heading': 'Reminder',
'body': "Don't forget me this weekend!"}}
</code></pre>
<p>it's designed for specific xml that is basically equivalent to json, should handle element attributes such as</p>
<pre><code><elementName attributeName='attributeContent'>elementContent</elementName>
</code></pre>
<p>too</p>
<p>there's the possibility of merging the attribute dictionary / subtag dictionary similarly to how repeat subtags are merged, although nesting the lists seems kind of appropriate :-)</p>
| 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('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 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 different ways is <a href="http://www.picklingtools.com/html/xmldoc.html" rel="nofollow">XML Support in Pickling Tools</a>. Version 1.3 and newer is required. It isn't pure Python (and in fact is designed to make C++ / Python interaction easier), but it might be appropriate for various use cases.</p>
| 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('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 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://stackoverflow.com/a/7684581/1395962</a></p>
<p><strong>Example:</strong></p>
<pre><code>import xml.etree.ElementTree as etree
from urllib import urlopen
xml_file = "http://your_xml_url"
tree = etree.parse(urlopen(xml_file))
root = tree.getroot()
def xml_to_dict(el):
d={}
if el.text:
d[el.tag] = el.text
else:
d[el.tag] = {}
children = el.getchildren()
if children:
d[el.tag] = map(xml_to_dict, children)
d.update(('@' + k, v) for k, v in el.attrib.iteritems())
return d
</code></pre>
<p>Call as</p>
<pre><code>xml_to_dict(root)
</code></pre>
| 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 action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.</p>
<p>I need the following operations: </p>
<ul>
<li>check if the transition has a label</li>
<li>get this label</li>
<li>add a label to a transition</li>
<li>check if the transition has a condition </li>
<li>get this condition</li>
<li>check for equality</li>
</ul>
<p>Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:</p>
<pre><code>class Transition(object):
def __init__(self, start, end):
self.start = start
self.end = end
def get_label(self):
return None
def has_label(self):
return False
def collect_decorations(self, decorations):
return decorations
def internal_equality(self, my_decorations, other):
try:
return (self.start == other.start
and self.end == other.end
and my_decorations = other.collect_decorations())
def __eq__(self, other):
return self.internal_equality(self.collect_decorations({}), other)
class Labeled(object):
def __init__(self, label, base):
self.base = base
self.label = label
def has_label(self):
return True
def get_label(self):
return self.label
def collect_decorations(self, decorations):
assert 'label' not in decorations
decorations['label'] = self.label
return self.base.collect_decorations(decorations)
def __getattr__(self, attribute):
return self.base.__getattr(attribute)
</code></pre>
<p>Is this a clean approach? Am I missing something?</p>
<p>I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:</p>
<pre><code>class Transition(object):
def __init__(self, **kwargs):
# init is pythons MI-madness ;-)
super(Transition, self).__init__(**kwargs)
self.start = kwargs['start']
self.end = kwargs['end']
def get_label(self):
return None
def get_condition(self):
return None
def __eq__(self, other):
try:
return self.start == other.start and self.end == other.end
except AttributeError:
return False
class LabeledTransition(Transition):
def __init__(self, **kwargs):
super(LabeledTransition).__init__(**kwargs)
self.label = kwargs['label']
def get_label(self):
return self.label
def __eq__(self):
super_result = super(LabeledTransition, self).__eq__(other)
try:
return super_result and self.label == other.label
except AttributeError:
return False
class ConditionalTransition(Transition):
def __init__(self, **kwargs):
super(ConditionalTransition, self).__init__(**kwargs)
self.condition = kwargs['condition']
def get_condition(self):
return self.condition
def __eq__(self, other):
super_result = super(ConditionalTransition, self).__eq__(other)
try:
return super_result and self.condition = other.condition
except AttributeError:
return False
# ConditionalTransition about the same, with get_condition
class LabeledConditionalTransition(LabeledTransition, ConditionalTransition):
pass
</code></pre>
<p>the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.</p>
<p>Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition.</p>
<p>So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?</p>
<p><em>EDIT</em>:
Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.</p>
| 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() function.</p>
<p>Can you post the code for the <code>ConditionalTransition</code> class? I think this would make it clearer.</p>
| 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 action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.</p>
<p>I need the following operations: </p>
<ul>
<li>check if the transition has a label</li>
<li>get this label</li>
<li>add a label to a transition</li>
<li>check if the transition has a condition </li>
<li>get this condition</li>
<li>check for equality</li>
</ul>
<p>Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:</p>
<pre><code>class Transition(object):
def __init__(self, start, end):
self.start = start
self.end = end
def get_label(self):
return None
def has_label(self):
return False
def collect_decorations(self, decorations):
return decorations
def internal_equality(self, my_decorations, other):
try:
return (self.start == other.start
and self.end == other.end
and my_decorations = other.collect_decorations())
def __eq__(self, other):
return self.internal_equality(self.collect_decorations({}), other)
class Labeled(object):
def __init__(self, label, base):
self.base = base
self.label = label
def has_label(self):
return True
def get_label(self):
return self.label
def collect_decorations(self, decorations):
assert 'label' not in decorations
decorations['label'] = self.label
return self.base.collect_decorations(decorations)
def __getattr__(self, attribute):
return self.base.__getattr(attribute)
</code></pre>
<p>Is this a clean approach? Am I missing something?</p>
<p>I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:</p>
<pre><code>class Transition(object):
def __init__(self, **kwargs):
# init is pythons MI-madness ;-)
super(Transition, self).__init__(**kwargs)
self.start = kwargs['start']
self.end = kwargs['end']
def get_label(self):
return None
def get_condition(self):
return None
def __eq__(self, other):
try:
return self.start == other.start and self.end == other.end
except AttributeError:
return False
class LabeledTransition(Transition):
def __init__(self, **kwargs):
super(LabeledTransition).__init__(**kwargs)
self.label = kwargs['label']
def get_label(self):
return self.label
def __eq__(self):
super_result = super(LabeledTransition, self).__eq__(other)
try:
return super_result and self.label == other.label
except AttributeError:
return False
class ConditionalTransition(Transition):
def __init__(self, **kwargs):
super(ConditionalTransition, self).__init__(**kwargs)
self.condition = kwargs['condition']
def get_condition(self):
return self.condition
def __eq__(self, other):
super_result = super(ConditionalTransition, self).__eq__(other)
try:
return super_result and self.condition = other.condition
except AttributeError:
return False
# ConditionalTransition about the same, with get_condition
class LabeledConditionalTransition(LabeledTransition, ConditionalTransition):
pass
</code></pre>
<p>the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.</p>
<p>Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition.</p>
<p>So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?</p>
<p><em>EDIT</em>:
Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.</p>
| 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):
self.name = name
def __repr__(self):
return self.name
class Automaton(object):
def __init__(self, instance, start):
self._state = start
self.transitions = instance.transitions()
def get_state(self):
return self._state
def set_state(self, target):
transition = self.transitions.get((self.state, target))
if transition:
action, condition = transition
if condition:
if condition():
if action:
action()
self._state = target
else:
self._state = target
else:
self._state = target
state = property(get_state, set_state)
class Door(object):
open = State('open')
closed = State('closed')
def __init__(self, blocked=False):
self.blocked = blocked
def close(self):
print 'closing door'
def do_open(self):
print 'opening door'
def not_blocked(self):
return not self.blocked
def transitions(self):
return {
(self.open, self.closed):(self.close, self.not_blocked),
(self.closed, self.open):(self.do_open, self.not_blocked),
}
if __name__ == '__main__':
door = Door()
automaton = Automaton(door, door.open)
print 'door is', automaton.state
automaton.state = door.closed
print 'door is', automaton.state
automaton.state = door.open
print 'door is', automaton.state
door.blocked = True
automaton.state = door.closed
print 'door is', automaton.state
</code></pre>
<p>the output of this programm would be:</p>
<pre><code>door is open
closing door
door is closed
opening door
door is open
door is open
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 311 | 2008-09-24T15:17:00Z | 127,825 | <p>What is the exact error you get? Is it like the following:</p>
<pre><code>>>> 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 input string on ".", and then add the microseconds to the datetime you got.</p>
<p>Try this:</p>
<pre><code>>>> def gt(dt_str):
dt, _, us= dt_str.partition(".")
dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
us= int(us.rstrip("Z"), 10)
return dt + datetime.timedelta(microseconds=us)
>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
>>>
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 311 | 2008-09-24T15:17:00Z | 127,972 | <p>Note in Python 2.6+ and Py3K, the %f character catches microseconds.</p>
<pre><code>>>> 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 of pythons datetime module.</p>
<p>Tests included! :P</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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>>>> import dateutil.parser
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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)
</code></pre>
<p>Test:</p>
<pre><code>from_utc("2007-03-04T21:08:12.123Z")
</code></pre>
<p>Result:</p>
<pre><code>datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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>>>> import arrow
>>> date = arrow.get("2008-09-03T20:56:35.450686Z")
>>> date.datetime
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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>>>> datetime.utcnow().replace(tzinfo=timezone(timedelta(0)))
... datetime.datetime(2015, 3, 11, 6, 2, 47, 879129, tzinfo=datetime.timezone.utc)
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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#datetime.datetime.strptime"><code>datetime.datetime.strptime</code></a> to parse RFC 3339 or ISO 8601 datetimes with timezones, like the one exhibited in the question:</p>
<pre><code>2008-09-03T20:56:35.450686Z
</code></pre>
<p>This is a bad idea.</p>
<p>Assuming that you want to support the full RFC 3339 format, including support for UTC offsets other than zero, then the code these answers suggest does not work. Indeed, it <em>cannot</em> work, because parsing RFC 3339 syntax using <code>strptime</code> is impossible. The format strings used by Python's datetime module are incapable of describing RFC 3339 syntax.</p>
<p>The problem is UTC offsets. The <a href="https://tools.ietf.org/html/rfc3339#section-5.6">RFC 3339 Internet Date/Time Format</a> requires that every date-time includes a UTC offset, and that those offsets can either be <code>Z</code> (short for "Zulu time") or in <code>+HH:MM</code> or <code>-HH:MM</code> format, like <code>+05:00</code> or <code>-10:30</code>.</p>
<p>Consequently, these are all valid RFC 3339 datetimes:</p>
<ul>
<li><code>2008-09-03T20:56:35.450686Z</code></li>
<li><code>2008-09-03T20:56:35.450686+05:00</code></li>
<li><code>2008-09-03T20:56:35.450686-10:30</code></li>
</ul>
<p>Alas, the format strings used by <code>strptime</code> and <code>strftime</code> have no directive that corresponds to UTC offsets in RFC 3339 format. A complete list of the directives they support can be found at <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior">https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior</a>, and the only UTC offset directive included in the list is <code>%z</code>:</p>
<blockquote>
<h3>%z</h3>
<p>UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).</p>
<p>Example: (empty), +0000, -0400, +1030</p>
</blockquote>
<p>This doesn't match the format of an RFC 3339 offset, and indeed if we try to use <code>%z</code> in the format string and parse an RFC 3339 date, we'll fail:</p>
<pre class="lang-none prettyprint-override"><code>>>> <b><i>from datetime import datetime</i></b>
>>> <b><i>datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%f%z")</b></i>
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
>>> <b><i>datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%f%z")</i></b>
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'</code></pre>
<p>(Actually, the above is just what you'll see in Python 3. In Python 2 we'll fail for an even simpler reason, which is that <a href="https://bugs.python.org/issue17342"><code>strptime</code> does not implement the <code>%z</code> directive at all in Python 2</a>.)</p>
<p>The multiple answers here that recommend <code>strptime</code> all work around this by including a literal <code>Z</code> in their format string, which matches the <code>Z</code> from the question asker's example datetime string (and discards it, producing a <code>datetime</code> object without a timezone):</p>
<pre class="lang-none prettyprint-override"><code>>>> <b><i>datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")</i></b>
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)</code></pre>
<p>Since this discards timezone information that was included in the original datetime string, it's questionable whether we should regard even this result as correct. But more importantly, because this approach involves <em>hard-coding a particular UTC offset into the format string</em>, it will choke the moment it tries to parse any RFC 3339 datetime with a different UTC offset:</p>
<pre class="lang-none prettyprint-override"><code>>>> <b><i>datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%fZ")</i></b>
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'</code></pre>
<p>Unless you're <em>certain</em> that you only need to support RFC 3339 datetimes in Zulu time, and not ones with other timezone offsets, don't use <code>strptime</code>. Use one of the many other approaches described in answers here instead.</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 libraries mentioned here, you could probably adapt <a href="https://github.com/django/django/blob/262d4db8c4c849b0fdd84550fb96472446cf90df/django/utils/dateparse.py#L84-L109">the Django source code for dateparse</a> to your project.</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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):
self.__offset = timedelta(minutes=offset)
hours, minutes = divmod(offset, 60)
#NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
# that have the opposite sign in the name;
# the corresponding numeric value is not used e.g., no minutes
self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)
def utcoffset(self, dt=None):
return self.__offset
def tzname(self, dt=None):
return self.__name
def dst(self, dt=None):
return timedelta(0)
def __repr__(self):
return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
def __getinitargs__(self):
return (self.__offset.total_seconds()/60,)
def parse_isoformat_datetime(isodatetime):
try:
return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
pass
try:
return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')
except ValueError:
pass
pat = r'(.*?[+-]\d{2}):(\d{2})'
temp = re.sub(pat, r'\1\2', isodatetime)
naive_date_str = temp[:-5]
offset_str = temp[-5:]
naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')
offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
if offset_str[0] == "-":
offset = -offset
return naive_dt.replace(tzinfo=FixedOffset(offset))
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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 > 0:
neg = 1
else:
neg = 0
tz = -tz
h, rem = divmod(tz, 3600)
m, rem = divmod(rem, 60)
if neg:
offset = '-%02d%02d' % (h, m)
else:
offset = '+%02d%02d' % (h, m)
return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset
dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')
timestamp = dt.timestamp()
return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)
</code></pre>
<p>Note that we should look if the string doesn't ends with <code>Z</code>, we could parse using <code>%z</code>.</p>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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><code>#!/usr/bin/env python
from __future__ import with_statement, division, print_function
import sqlite3
import datetime
testtimes = [
"2016-08-25T16:01:26.123456Z",
"2016-08-25T16:01:29",
]
db = sqlite3.connect(":memory:")
c = db.cursor()
for timestring in testtimes:
c.execute("SELECT strftime('%s', ?)", (timestring,))
converted = c.fetchone()[0]
print("%s is %s after epoch" % (timestring, converted))
dt = datetime.datetime.fromtimestamp(int(converted))
print("datetime is %s" % dt)
</code></pre>
<p>Output:</p>
<pre><code>2016-08-25T16:01:26.123456Z is 1472140886 after epoch
datetime is 2016-08-25 12:01:26
2016-08-25T16:01:29 is 1472140889 after epoch
datetime is 2016-08-25 12:01:29
</code></pre>
| 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 standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| 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=<UTC>)
</code></pre>
<p>So it could be used for parsing iso-8601 dates in fields within entire project:</p>
<pre><code>from django.utils import formats
from django.forms.fields import DateTimeField
from django.utils.dateparse import parse_datetime
class DateTimeFieldFixed(DateTimeField):
def strptime(self, value, format):
if format == 'iso-8601':
return parse_datetime(value)
return super().strptime(value, format)
DateTimeField.strptime = DateTimeFieldFixed.strptime
formats.ISO_INPUT_FORMATS['DATETIME_INPUT_FORMATS'].insert(0, 'iso-8601')
</code></pre>
| 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 different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| 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>
<pre><code>{ 'id1': [ ('description1a', 'type1'), ('description1b','type1') ],
'id2': [ ('description2', 'type2') ],
...
}
</code></pre>
<p>This sure seems minimal. ID's are only represented once.</p>
<p>Perhaps you have something like this?</p>
<pre><code>{ 'id1': ( ('description1a', 'description1b' ), 'type1' ),
'id2': ( ('description2',), 'type2' ),
...
}
</code></pre>
<p>I'm not sure you can find anything more compact unless you resort to using the <code>struct</code> module.</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 different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| 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 different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| 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, you'd have to subclass tuple and override the hashcode method:</p>
<pre><code>class ProteinTuple(tuple):
def __new__(cls, m1, m2, m3):
return tuple.__new__(cls, (m1, m2, m3))
def __hash__(self):
return hash(self[0])
</code></pre>
<p>Keep in mind that you pay for the extra function call to <code>__hash__</code> in this case, because otherwise it would be a C method.</p>
<p>I'd go for Constantin's suggestions and take out the id from the tuple and see how much that helps.</p>
| 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 different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| 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 is how to structure your data in one process to use less memory. The one canonical answer to this is (as long as you still need associative lookups), use as little other structures then python strings (str, not unicode) as possible. A python hash (dictionary) stores the references to your strings fairly efficiently (it is not a b-tree implementation).</p>
<p>However I think that you will not get very far with that approach, since what you face are huge datasets that might eventually just exceed the process address space and the physical memory of the machine you're working with altogether.</p>
<h2>Alternative Solution</h2>
<p>I would propose a different solution that does not involve changing your data structure to something that is harder to insert or interprete.</p>
<ul>
<li>Split your information up in multiple processes, each holding whatever datastructure is convinient for that. </li>
<li>Implement inter process communication with sockets such that processes might reside on other machines altogether. </li>
<li>Try to divide your data such as to minimize inter process communication (i/o is glacially slow compared to cpu cycles). </li>
</ul>
<p>The advantage of the approach I outline is that</p>
<ul>
<li>You get to use two ore more cores on a machine fully for performance</li>
<li>You are not limited by the address space of one process, or even the physical memory of one machine</li>
</ul>
<p>There are numerous packages and aproaches to distributed processing, some of which are</p>
<ul>
<li><a href="http://pypi.python.org/pypi/linda/0.5.1" rel="nofollow">linda</a></li>
<li><a href="http://pypi.python.org/pypi/processing/0.52" rel="nofollow">processing</a></li>
</ul>
| 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 different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| 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 think a mapping might be too big. Do you have any evidence of this? Don't over-optimize without actual measurements. </p>
<p>This may be (if I'm guessing correctly) the standard "merge" operation from multiple sources.</p>
<pre><code>source1.sort()
source2.sort()
result= []
while len(source1) > 0 or len(source2) > 0:
if len(source1) == 0:
result.append( source2.pop(0) )
elif len(source2) == 0:
result.append( source1.pop(0) )
elif source1[0][0] < source2[0][0]:
result.append( source1.pop(0) )
elif source2[0][0] < source1[0][0]:
result.append( source2.pop(0) )
else:
# keys are equal
result.append( source1.pop(0) )
# check for source2, to see if the description is different.
</code></pre>
<p>This assembles a union of two lists by sorting and merging. No mapping, no hash.</p>
| 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 different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| 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 ):
keyPos= 0
for s in sources:
s.sort()
while any( [len(s)>0 for s in sources] ):
topEnum= enumerate([ s[0][keyPos] if len(s) > 0 else None for s in sources ])
top= [ t for t in topEnum if t[1] is not None ]
top.sort( key=lambda a:a[1] )
src, key = top[0]
#print src, key
yield sources[ src ].pop(0)
</code></pre>
<p>This generator removes duplicates from a sequence. </p>
<pre><code>def unique( sequence ):
keyPos= 0
seqIter= iter(sequence)
curr= seqIter.next()
for next in seqIter:
if next[keyPos] == curr[keyPos]:
# might want to create a sub-list of matches
continue
yield curr
curr= next
yield curr
</code></pre>
<p>Here's a script which uses these functions to produce a resulting sequence which is the union of all the sources with duplicates removed.</p>
<pre><code>for u in unique( merge( source1, source2, source3, ... ) ):
print u
</code></pre>
<p>The complete set of data in each sequence must exist in memory once because we're sorting in memory. However, the resulting sequence does not actually exist in memory. Indeed, it works by consuming the other sequences. </p>
| 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" rel="nofollow">backwards-incompatible changes</a> to see how to fix the issue.</p>
| 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.</p></li>
<li><p>A small set of template changes, most notably auto-escaping.</p></li>
<li><p>Anything that depends on the specific structure of Django's internals. This shouldn't be an issue unless you're doing stuff like dynamically modifying Django internals to change their behavior in a way that's necessary/convenient for your project.</p></li>
</ol>
<p>To summarize, unless you're doing a lot of really weird and/or complex stuff, a simple upgrade should be relatively painless and only require a few changes.</p>
| 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, <strong>str</strong>() to <strong>unicode</strong>() and maxlength to max_length</p>
<p>Most of the other changes were new features or backend rewrites or stuff that as someone who was building basic websites did not even get near.</p>
| 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 bytestrings and change this to unicode. Worst case is the template rendering, you'll never know you forgot to change one variable until you get UnicodeError.</p>
<p>Other notable thing: manipulators (<em>oldforms</em>) have gone and you have no other way than to rewrite all parts with forms (<em>newforms</em>).</p>
<p>If this is your case and your project is larger than 2-3 apps, I'd be rather reluctant to upgrade until really necessary.</p>
| 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>
<li>refactor the application into
reusable apps, add tests. That left us with
40.000 LoC in the main application/Project</li>
<li>Upgrade to django 0.97-post autoexcape merge. Fix auto escaping in the reusable apps created in 3. Then fix the remaining auto-escaping issues in the mian application. </li>
<li>Upgrade to 1.0. What was left was mostly fixing the admin stuff.</li>
</ol>
<p>The whole thing took about 6 months where we where running a legacy production branch on our servers while porting an other branch to 1.0. While doing so we also where adding features to the production branch.</p>
<p>The final merge was much less messy than expected and took about a week for 4 coders merging, reviewing, testing and fixing. We then rolled out, and for about a week got bitten by previously unexpected bugs.</p>
<p>All in all I'm quite satisfied with the outcome. We have a much better codebase now for further development. </p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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-c849d5d5d94bc3eacbff9d5746af4083443cf2ca">this link</a> for a lazy-loading technique that combines the best of both approaches by doing a "lazy import".</p>
<p>But there are reasons other than efficiency why you might prefer one over the other. One approach is makes it much more clear to someone reading the code as to the dependencies that this module has. They also have very different failure characteristics -- the first will fail at load time if there's no "datetime" module while the second won't fail until the method is called.</p>
<p><strong>Added Note:</strong> In IronPython, imports can be quite a bit more expensive than in CPython because the code is basically being compiled as it's being imported.</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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, it makes it much easier to tell what function or object came from what module.</p>
<p>One good reason to import a module elsewhere in the code is if it's used in a debugging statement.</p>
<p>For example:</p>
<pre><code>do_something_with_x(x0
</code></pre>
<p>I could debug this with:</p>
<pre><code>from pprint import pprint
pprint(x)
do_something_with_x(x)
</code></pre>
<p>Of course, the other reason to import modules elsewhere in the code is if you need to dynamically import them. This is because you pretty much don't have any choice.</p>
<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>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 foo
aa = foo.xyz() # initiate something for the test
</code></pre>
<p>Secondly, you might have a requirement to conditionally import some different module at runtime.</p>
<pre><code>if [condition]:
import foo as plugin_api
else:
import bar as plugin_api
xx = plugin_api.Plugin()
[...]
</code></pre>
<p>There are probably other situations where you might place imports in other parts in the code.</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 call after the first one is still incurring the additional overhead of doing the import. </p>
<p>Case 2 save some execution time and latency by importing datetime beforehand so that not_often_called() will return more quickly when it <em>is</em> called, and also by not incurring the overhead of an import on every call.</p>
<p>Besides efficiency, it's easier to see module dependencies up front if the import statements are ... up front. Hiding them down in the code can make it more difficult to easily find what modules something depends on.</p>
<p>Personally I generally follow the PEP except for things like unit tests and such that I don't want always loaded because I <em>know</em> they aren't going to be used except for test code.</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 unexpected times, it probably makes more sense to load them dynamically with the <code>__import__</code> function, and be <b>sure</b> to catch <code>ImportError</code> exceptions, and handle them in a reasonable manner.</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you <strong>did</strong> profile to see where best to improve performance, right??)</p>
<p><hr /></p>
<p>The best reasons I've seen to perform lazy imports are:</p>
<ul>
<li>Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed.</li>
<li>In the <code>__init__.py</code> of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use <code>bzrlib</code>'s lazy-loading framework.</li>
</ul>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 terminate(process):
kill(process.pid, SIGTERM)
except (AttributeError, ImportError):
try:
from win32api import TerminateProcess # use win32api if available
def terminate(process):
TerminateProcess(int(process._handle), -1)
except ImportError:
def terminate(process):
raise NotImplementedError # define a dummy function
</code></pre>
<p>(On review: what <a href="http://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module#128577">John Millikin</a> said.)</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 other imports:</p>
<pre><code>from foo import bar
from baz import qux
# Note: datetime is imported in SomeClass below
</code></pre>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 statement would cost very little then since the module intialization would have happened already. All it is doing at this point is binding the existing module object to the local scope.</p>
<p>Couple that information with the argument for readability and I would say that it is best to have the import statement at module scope. </p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 testing intact. If I have my imports at the top of the module, when I move a function, I find that I end up spending a lot of time getting the new module's imports complete and minimal. A refactoring IDE might make this irrelevant.</p>
<p>There is a speed penalty as mentioned elsewhere. I have measured this in my application and found it to be insignificant for my purposes. </p>
<p>It is also nice to be able to see all module dependencies up front without resorting to search (e.g. grep). However, the reason I care about module dependencies is generally because I'm installing, refactoring, or moving an entire system comprising multiple files, not just a single module. In that case, I'm going to perform a global search anyway to make sure I have the system-level dependencies. So I have not found global imports to aid my understanding of a system in practice.</p>
<p>I usually put the import of <code>sys</code> inside the <code>if __name__=='__main__'</code> check and then pass arguments (like <code>sys.argv[1:]</code>) to a <code>main()</code> function. This allows me to use <code>main</code> in a context where <code>sys</code> has not been imported.</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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> and b <code>y()</code>, respectively. Then:</p>
<ol>
<li>We can move one of the <code>from imports</code> at the bottom of the module.</li>
<li>We can move one of the <code>from imports</code> inside the function or method that is actually requiring the import (this isn't always possible, as you may use it from several places).</li>
<li>We can change one of the two <code>from imports</code> to be an import that looks like: <code>import a</code></li>
</ol>
<p>So, to conclude. If you aren't dealing with circular dependencies and doing some kind of trick to avoid them, then it's better to put all your imports at the top because of the reasons already explained in other answers to this question. And please, when doing this "tricks" include a comment, it's always welcome! :)</p>
| 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 used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
| 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>This issue often comes up in Apache Spark's Python API, where you need to initialize the SparkContext before importing any pyspark packages or modules. It's best to place pyspark imports in a scope where the SparkContext is guaranteed to be available.</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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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 attribute value and be done with it.</p>
<p>A property should only be used if there's something to conceal -- something that might change in a future implementation. </p>
<p>Maybe your example is way stripped down, and there is some hellish calculation you've left off. But it doesn't look like the property adds significant value.</p>
<p>The Java-influenced "privacy" techniques (in Python, attribute names that begin with _) aren't really very helpful. Private from whom? The point of private is a little nebulous when you have the source (as you do in Python.)</p>
<p>The Java-influenced EJB-style getters and setters (often done as properties in Python) are there to facilitate Java's primitive introspection as well as to pass muster with the static language compiler. All those getters and setters aren't as helpful in Python.</p>
| -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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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):
return self.fget()
def __set__(self, instance, value):
self.fset(value)
class Foo(object):
_bar = 1
def get_bar():
print 'getting'
return Foo._bar
def set_bar(value):
print 'setting'
Foo._bar = value
bar = ClassProperty(get_bar, set_bar)
f = Foo()
#__get__ works
f.bar
Foo.bar
f.bar = 2
Foo.bar = 3 #__set__ does not
</code></pre>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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):
self.getter = getter
self.setter = setter
def __get__(self, cls, owner):
return getattr(cls, self.getter)()
def __set__(self, cls, value):
getattr(cls, self.setter)(value)
class MetaFoo(type):
var = ClassProperty('getvar', 'setvar')
class Foo(object):
__metaclass__ = MetaFoo
_var = 5
@classmethod
def getvar(cls):
print "Getting var =", cls._var
return cls._var
@classmethod
def setvar(cls, value):
print "Setting var =", value
cls._var = value
x = Foo.var
print "Foo.var = ", x
Foo.var = 42
x = Foo.var
print "Foo.var = ", x
</code></pre>
<p>The knot of the issue is that properties are what Python calls "descriptors". There is no short and easy way to explain how this sort of metaprogramming works, so I must point you to the <a href="http://users.rcn.com/python/download/Descriptor.htm">descriptor howto</a>.</p>
<p>You only ever need to understand this sort of things if you are implementing a fairly advanced framework. Like a transparent object persistence or RPC system, or a kind of domain-specific language.</p>
<p>However, in a comment to a previous answer, you say that you </p>
<blockquote>
<p>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>It seems to me, what you really want is an <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer</a> design pattern.</p>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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 think of a way to do it then:</p>
<pre><code>class MyClass (object):
__var = None
def _set_var (self, value):
type (self).__var = value
def _get_var (self):
return self.__var
var = property (_get_var, _set_var)
a = MyClass ()
b = MyClass ()
a.var = "foo"
print b.var
</code></pre>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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>>>> class foo(object):
... _var = 5
... def getvar(cls):
... return cls._var
... getvar = classmethod(getvar)
... def setvar(cls, value):
... cls._var = value
... setvar = classmethod(setvar)
... var = property(lambda self: self.getvar(), lambda self, val: self.setvar(val))
...
>>> f = foo()
>>> f.var
5
>>> f.var = 3
>>> f.var
3
</code></pre>
<p>The <code>property</code> function needs two <code>callable</code> arguments. give them lambda wrappers (which it passes the instance as its first argument) and all is well.</p>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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). If you
want to override the __get__ operation
for properties when used as a class
attribute, you can subclass property -
it is a new-style type itself - to
extend its __get__ method, or you can
define a descriptor type from scratch
by creating a new-style class that
defines __get__, __set__ and
__delete__ methods.</p>
</blockquote>
<p><strong>NOTE: The below method doesn't actually work for setters, only getters.</strong></p>
<p>Therefore, I believe the prescribed solution is to create a ClassProperty as a subclass of property.</p>
<pre><code>class ClassProperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class foo(object):
_var=5
def getvar(cls):
return cls._var
getvar=classmethod(getvar)
def setvar(cls,value):
cls._var=value
setvar=classmethod(setvar)
var=ClassProperty(getvar,setvar)
assert foo.getvar() == 5
foo.setvar(4)
assert foo.getvar() == 4
assert foo.var == 4
foo.var = 3
assert foo.var == 3
</code></pre>
<p>However, the setters don't actually work:</p>
<pre><code>foo.var = 4
assert foo.var == foo._var # raises AssertionError
</code></pre>
<p><code>foo._var</code> is unchanged, you've simply overwritten the property with a new value.</p>
<p>You can also use <code>ClassProperty</code> as a decorator:</p>
<pre><code>class Foo(object):
_var = 5
@ClassProperty
@classmethod
def var(cls):
return cls._var
@var.setter
@classmethod
def var(cls, value):
cls._var = value
assert foo.var == 5
</code></pre>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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>>>> class foo(object):
_var = 5
class __metaclass__(type):
pass
@classmethod
def getvar(cls):
return cls._var
@classmethod
def setvar(cls, value):
cls._var = value
>>> foo.__metaclass__.var = property(foo.getvar.im_func, foo.setvar.im_func)
>>> foo.var
5
>>> foo.var = 3
>>> foo.var
3
</code></pre>
<p>But since you're using a metaclass anyway, it will read better if you just move the classmethods in there.</p>
<pre><code>>>> class foo(object):
_var = 5
class __metaclass__(type):
@property
def var(cls):
return cls._var
@var.setter
def var(cls, value):
cls._var = value
>>> foo.var
5
>>> foo.var = 3
>>> foo.var
3
</code></pre>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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 classproperty(property):
def __get__(self, obj, type_):
return self.fget.__get__(None, type_)()
def __set__(self, obj, value):
cls = type(obj)
return self.fset.__get__(None, cls)(value)
class A (object):
_foo = 1
@classproperty
@classmethod
def foo(cls):
return cls._foo
@foo.setter
@classmethod
def foo(cls, value):
cls.foo = value
a = A()
print a.foo
b = A()
print b.foo
b.foo = 5
print a.foo
A.foo = 10
print b.foo
print A.foo
</code></pre>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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(object):
@classproperty
def x(cls):
return 1
assert C.x == 1
assert C().x == 1
</code></pre>
| 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>>>> class foo(object):
... _var=5
... def getvar(cls):
... return cls._var
... getvar=classmethod(getvar)
... def setvar(cls,value):
... cls._var=value
... setvar=classmethod(setvar)
... var=property(getvar,setvar)
...
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the property() function with classmethod decorated functions?</p>
| 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 you can derive the class from the instance, you can can get whatever desired behavior you might want from a class-property with <code>property</code>:</p>
<pre><code>class Example(object):
_class_property = None
@property
def class_property(self):
return self._class_property
@class_property.setter
def class_property(self, value):
type(self)._class_property = value
@class_property.deleter
def class_property(self):
del type(self)._class_property
</code></pre>
<p>This code can be used to test - it should pass without raising any errors:</p>
<pre><code>ex1 = Example()
ex2 = Example()
ex1.class_property = None
ex2.class_property = 'Example'
assert ex1.class_property is ex2.class_property
del ex2.class_property
assert not hasattr(ex1, 'class_property')
</code></pre>
<p>And note that we didn't need metaclasses at all - and you don't directly access a metaclass through its classes' instances anyways.</p>
| 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). You may learn more and have better control if you put together your own using SQLAlchemy or SQLObject, woth of which work great with TurboGears.</p>
| 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 enjoy working with it.</p>
<p>Hope that helps you :)</p>
| 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/pypi/Catwalk" rel="nofollow">Catwalk2</a>, a default config of tgext.admin that is aware of your quickstarted model.</li>
<li><a href="http://www.turbogears.org/2.0/docs/main/Extensions/Admin/index.html#adding-admincontroller-to-your-tg-application" rel="nofollow">AdminController</a>, this will take all your models (or a list of them) and create CRUD for all of them.</li>
<li><a href="http://turbogears.org/2.0/docs/main/Extensions/Crud/index.html" rel="nofollow">CrudRestController</a>, will take one object and create CRUD for it.</li>
<li><a href="http://turbogears.org/2.0/docs/main/RestControllers.html" rel="nofollow">RestController</a>, will take one object and give you only the REST API, that is no forms or data display.</li>
<li>plain <a href="http://sprox.org" rel="nofollow">Sprox</a>, you will give it an object and and depending on the base class you use you will get the neww form or the edit for or the table view or the single record view.</li>
</ul>
| 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-response/#django.http.HttpResponse.set_cookie" rel="nofollow">documentation</a>, I can't tell if this is possible. It looks like it just takes a string, so is there another way?</p>
<p>I've tried passing it an array (<code>[10, 20, 30]</code>) and dictionary (<code>{'name': 'Scott', 'id': 1}</code>) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.</p>
| 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 using multiple cookies. Keep the over-the-wire overhead down by doing what you're doing.</p>
| 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-response/#django.http.HttpResponse.set_cookie" rel="nofollow">documentation</a>, I can't tell if this is possible. It looks like it just takes a string, so is there another way?</p>
<p>I've tried passing it an array (<code>[10, 20, 30]</code>) and dictionary (<code>{'name': 'Scott', 'id': 1}</code>) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.</p>
| 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-response/#django.http.HttpResponse.set_cookie" rel="nofollow">documentation</a>, I can't tell if this is possible. It looks like it just takes a string, so is there another way?</p>
<p>I've tried passing it an array (<code>[10, 20, 30]</code>) and dictionary (<code>{'name': 'Scott', 'id': 1}</code>) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.</p>
| 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 exactly the same as what you're looking for, but it could work if you don't mind a small amount of db overhead.</p>
| 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-response/#django.http.HttpResponse.set_cookie" rel="nofollow">documentation</a>, I can't tell if this is possible. It looks like it just takes a string, so is there another way?</p>
<p>I've tried passing it an array (<code>[10, 20, 30]</code>) and dictionary (<code>{'name': 'Scott', 'id': 1}</code>) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.</p>
| 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:
self.values = pickle.loads(cookie)
except:
# assume that it used to just hold a string value
self.values = cookie
elif values != None:
self.values = values
else:
self.values = None
def __str__(self):
return pickle.dumps(self.values)
</code></pre>
<p>Then, you can get the cookie:</p>
<pre><code>newcookie = MultiCookie(cookie=request.COOKIES.get('multi'))
values_for_cookie = newcookie.values
</code></pre>
<p>Or set the values:</p>
<pre><code>mylist = [ 1, 2, 3 ]
newcookie = MultiCookie(values=mylist)
request.set_cookie('multi',value=newcookie)
</code></pre>
| 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 that the usermod easily allows me to add a user to a supplementary group with this command:</p>
<pre><code>usermod -a -G supgroup1,supgroup2 username
</code></pre>
<p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p>
<p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p>
<pre><code>#!/usr/bin/perl
#
# Usage: removegroup.pl login group
# Purpose: Removes a user from a group while retaining current primary and
# supplementary groups.
# Notes: There is a Debian specific utility that can do this called deluser,
# but I did not want any cross-distribution dependencies
#
# Date: 25 September 2008
# Validate Arguments (correct number, format etc.)
if ( ($#ARGV < 1) || (2 < $#ARGV) ) {
print "\nUsage: removegroup.pl login group\n\n";
print "EXIT VALUES\n";
print " The removeuser.pl script exits with the following values:\n\n";
print " 0 success\n\n";
print " 1 Invalid number of arguments\n\n";
print " 2 Login or Group name supplied greater than 16 characters\n\n";
print " 3 Login and/or Group name contains invalid characters\n\n";
exit 1;
}
# Check for well formed group and login names
if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1])))
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and Group names must be less than 16 Characters\n";
exit 2;
}
if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) )
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and/or Group name contains invalid characters\n";
exit 3;
}
# Set some variables for readability
$login=$ARGV[0];
$group=$ARGV[1];
# Requires the GroupFile interface from perl-Unix-Configfile
use Unix::GroupFile;
$grp = new Unix::GroupFile "/etc/group";
$grp->remove_user("$group", "$login");
$grp->commit();
undef $grp;
exit 0;
</code></pre>
| 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 feed that back to <em>usermod</em>.</p>
| 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 that the usermod easily allows me to add a user to a supplementary group with this command:</p>
<pre><code>usermod -a -G supgroup1,supgroup2 username
</code></pre>
<p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p>
<p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p>
<pre><code>#!/usr/bin/perl
#
# Usage: removegroup.pl login group
# Purpose: Removes a user from a group while retaining current primary and
# supplementary groups.
# Notes: There is a Debian specific utility that can do this called deluser,
# but I did not want any cross-distribution dependencies
#
# Date: 25 September 2008
# Validate Arguments (correct number, format etc.)
if ( ($#ARGV < 1) || (2 < $#ARGV) ) {
print "\nUsage: removegroup.pl login group\n\n";
print "EXIT VALUES\n";
print " The removeuser.pl script exits with the following values:\n\n";
print " 0 success\n\n";
print " 1 Invalid number of arguments\n\n";
print " 2 Login or Group name supplied greater than 16 characters\n\n";
print " 3 Login and/or Group name contains invalid characters\n\n";
exit 1;
}
# Check for well formed group and login names
if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1])))
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and Group names must be less than 16 Characters\n";
exit 2;
}
if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) )
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and/or Group name contains invalid characters\n";
exit 3;
}
# Set some variables for readability
$login=$ARGV[0];
$group=$ARGV[1];
# Requires the GroupFile interface from perl-Unix-Configfile
use Unix::GroupFile;
$grp = new Unix::GroupFile "/etc/group";
$grp->remove_user("$group", "$login");
$grp->commit();
undef $grp;
exit 0;
</code></pre>
| 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 that the usermod easily allows me to add a user to a supplementary group with this command:</p>
<pre><code>usermod -a -G supgroup1,supgroup2 username
</code></pre>
<p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p>
<p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p>
<pre><code>#!/usr/bin/perl
#
# Usage: removegroup.pl login group
# Purpose: Removes a user from a group while retaining current primary and
# supplementary groups.
# Notes: There is a Debian specific utility that can do this called deluser,
# but I did not want any cross-distribution dependencies
#
# Date: 25 September 2008
# Validate Arguments (correct number, format etc.)
if ( ($#ARGV < 1) || (2 < $#ARGV) ) {
print "\nUsage: removegroup.pl login group\n\n";
print "EXIT VALUES\n";
print " The removeuser.pl script exits with the following values:\n\n";
print " 0 success\n\n";
print " 1 Invalid number of arguments\n\n";
print " 2 Login or Group name supplied greater than 16 characters\n\n";
print " 3 Login and/or Group name contains invalid characters\n\n";
exit 1;
}
# Check for well formed group and login names
if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1])))
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and Group names must be less than 16 Characters\n";
exit 2;
}
if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) )
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and/or Group name contains invalid characters\n";
exit 3;
}
# Set some variables for readability
$login=$ARGV[0];
$group=$ARGV[1];
# Requires the GroupFile interface from perl-Unix-Configfile
use Unix::GroupFile;
$grp = new Unix::GroupFile "/etc/group";
$grp->remove_user("$group", "$login");
$grp->commit();
undef $grp;
exit 0;
</code></pre>
| 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 execrcise for the reader.</p>
| 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 that the usermod easily allows me to add a user to a supplementary group with this command:</p>
<pre><code>usermod -a -G supgroup1,supgroup2 username
</code></pre>
<p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p>
<p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p>
<pre><code>#!/usr/bin/perl
#
# Usage: removegroup.pl login group
# Purpose: Removes a user from a group while retaining current primary and
# supplementary groups.
# Notes: There is a Debian specific utility that can do this called deluser,
# but I did not want any cross-distribution dependencies
#
# Date: 25 September 2008
# Validate Arguments (correct number, format etc.)
if ( ($#ARGV < 1) || (2 < $#ARGV) ) {
print "\nUsage: removegroup.pl login group\n\n";
print "EXIT VALUES\n";
print " The removeuser.pl script exits with the following values:\n\n";
print " 0 success\n\n";
print " 1 Invalid number of arguments\n\n";
print " 2 Login or Group name supplied greater than 16 characters\n\n";
print " 3 Login and/or Group name contains invalid characters\n\n";
exit 1;
}
# Check for well formed group and login names
if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1])))
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and Group names must be less than 16 Characters\n";
exit 2;
}
if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) )
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and/or Group name contains invalid characters\n";
exit 3;
}
# Set some variables for readability
$login=$ARGV[0];
$group=$ARGV[1];
# Requires the GroupFile interface from perl-Unix-Configfile
use Unix::GroupFile;
$grp = new Unix::GroupFile "/etc/group";
$grp->remove_user("$group", "$login");
$grp->commit();
undef $grp;
exit 0;
</code></pre>
| 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>Remove users from a group with the same command, but a -d switch rather than -a:</p>
<p>gpasswd -d userid mygroup </p>
<p>"man gpasswd" for more info...</p>
<p>I looked for ages to find this. Sometimes it takes too much effort not to reinvent the wheel...</p>
| 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>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</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 like this:</p>
<pre><code>ignore_errors (baz, [
(lambda: foo (a, b)),
(lambda: bar (c, d)),
])
</code></pre>
| 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>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</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 look right in practice:</p>
<pre><code>handle_exception(foo, baz, a, b)
handle_exception(bar, baz, c, d)
</code></pre>
| 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>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</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>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</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></pre>
<p>Your example now becomes:</p>
<pre><code>with handler():
foo(a, b)
with handler():
bar(c, d)
</code></pre>
| 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>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</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, b )
TryOrBaz( bar )( c, d )
</code></pre>
| 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>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</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)
except Exception, e:
handler(e)
return call_function
return decorate
def baz(e):
print(e)
@handle_exception(baz)
def foo(a, b):
return a + b
@handle_exception(baz)
def bar(c, d):
return c.index(d)
</code></pre>
<p>Usage:</p>
<pre><code>>>> foo(1, '2')
unsupported operand type(s) for +: 'int' and 'str'
>>> bar('steve', 'cheese')
substring not found
</code></pre>
| 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.assertRaises(SomeCoolException, mymod.myfunc)
</code></pre>
| 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('ExpectedException not raised')
</code></pre>
<p>On Python < 2.7 this construct is useful for checking for specific values in the expected exception. The unittest function <code>assertRaises</code> only checks if an exception was raised.</p>
| 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):
self.assertRaises(ExpectedException, afunction, arg1, arg2)
</code></pre>
| 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):
"""
>>> throw_up('Fish n Chips')
Traceback (most recent call last):
...
Exception: Fish n Chips
>>> throw_up('Fish n Chips', gowrong=True)
'I feel fine!'
"""
if gowrong:
return "I feel fine!"
raise Exception(something)
if __name__ == '__main__':
import doctest
doctest.testmod()
</code></pre>
<p>If you put this example in a module and run it from the command line both test cases are evaluated and checked.</p>
<p>[1] <a href="http://docs.python.org/lib/module-doctest.html">Python documentation: 23.2 doctest -- Test interactive Python examples</a></p>
| 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>
<pre><code>from testcase import TestCase
import mymod
class MyTestCase(TestCase):
def test1(self):
self.assertRaisesWithMessage(SomeCoolException,
'expected message',
mymod.myfunc)
</code></pre>
| 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:
broken_function()
self.assertTrue('This is broken' in context.exception)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p><a href="http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises">http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises</a></p>
<hr>
<p>In <strong>Python 3.5</strong>, you have to wrap <code>context.exception</code> in <code>str</code>, otherwise you'll get a <code>TypeError</code></p>
<pre><code>self.assertTrue('This is broken' in str(context.exception))
</code></pre>
| 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 passing the method to assertRaises
self.assertRaises(Exception, test_class.raises_exception)
</code></pre>
| -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 square value of a.
"""
try:
out = a*a
except TypeError:
raise TypeError("Input should be a string:")
return out
</code></pre>
<p>Here is the test to be performed (only this test is inserted):</p>
<pre><code>import dum_function as df # import function module
import unittest
class Test(unittest.TestCase):
"""
The class inherits from unittest
"""
def setUp(self):
"""
This method is called before each test
"""
self.false_int = "A"
def tearDown(self):
"""
This method is called after each test
"""
pass
#---
## TESTS
def test_square_value(self):
# assertRaises(excClass, callableObj) prototype
self.assertRaises(TypeError, df.square_value(self.false_int))
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>We are now ready to test our function! Here is what happens when trying to run the test :</p>
<pre><code>======================================================================
ERROR: test_square_value (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_dum_function.py", line 22, in test_square_value
self.assertRaises(TypeError, df.square_value(self.false_int))
File "/home/jlengrand/Desktop/function.py", line 8, in square_value
raise TypeError("Input should be a string:")
TypeError: Input should be a string:
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
</code></pre>
<p>The TypeError is actullay raised, and generates a test failure. The problem is that this is exactly the behavior we wanted :s.</p>
<p>To avoid this error, simply run the function using lambda in the test call :</p>
<pre><code>self.assertRaises(TypeError, lambda: df.square_value(self.false_int))
</code></pre>
<p>The final output :</p>
<pre><code>----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
</code></pre>
<p>Perfect !</p>
<p>... and for me is perfect too!!</p>
<p>Thansk a lot Mr. Julien Lengrand-Lambert</p>
| 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 <code>raises</code> like this:</p>
<pre><code>with raises(Exception):
print "Hola" # Calls assert False
with raises(Exception):
raise Exception # Calls assert True
</code></pre>
<p>If you are using <code>pytest</code>, this thing is implemented already. You can do <code>pytest.raises(Exception)</code>:</p>
<p>Example:</p>
<pre><code>def test_div_zero():
with pytest.raises(ZeroDivisionError):
1/0
</code></pre>
<p>And the result:</p>
<pre><code>pigueiras@pigueiras$ py.test
================= test session starts =================
platform linux2 -- Python 2.6.6 -- py-1.4.20 -- pytest-2.5.2 -- /usr/bin/python
collected 1 items
tests/test_div_zero.py:6: test_div_zero PASSED
</code></pre>
| 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>
<pre><code> def test_1_cannot_add_int_and_str(self):
with self.assertRaises(TypeError):
1 + '1'
</code></pre>
<h1>Demonstration</h1>
<p>The best practice approach is fairly easy to demonstrate in a Python shell. </p>
<p><strong>The <code>unittest</code> library</strong></p>
<p>In Python 2.7 or 3:</p>
<pre><code>import unittest
</code></pre>
<p>In Python 2.6, you can install a backport of 2.7's <code>unittest</code> library, called <a href="https://pypi.python.org/pypi/unittest2">unittest2</a>, and just alias that as <code>unittest</code>:</p>
<pre><code>import unittest2 as unittest
</code></pre>
<h1>Example tests</h1>
<p>Now, paste into your Python shell the following test of Python's type-safety:</p>
<pre><code>class MyTestCase(unittest.TestCase):
def test_1_cannot_add_int_and_str(self):
with self.assertRaises(TypeError):
1 + '1'
def test_2_cannot_add_int_and_str(self):
import operator
self.assertRaises(TypeError, operator.add, 1, '1')
</code></pre>
<p>Test one uses <code>assertRaises</code> as a context manager, which ensures that the error is properly caught and cleaned up, while recorded. </p>
<p>We could also write it <em>without</em> the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function. </p>
<p>I think it's far more simple, readable, and maintainable to just to use the context manager.</p>
<h1>Running the tests</h1>
<p>To run the tests:</p>
<pre><code>unittest.main(exit=False)
</code></pre>
<p>In Python 2.6, you'll probably <a href="http://stackoverflow.com/a/21262077/541136">need the following</a>:</p>
<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))
</code></pre>
<p>And your terminal should output the following:</p>
<pre><code>..
----------------------------------------------------------------------
Ran 2 tests in 0.007s
OK
<unittest2.runner.TextTestResult run=2 errors=0 failures=0>
</code></pre>
<p>And we see that as we expect, attempting to add a <code>1</code> and a <code>'1'</code> result in a <code>TypeError</code>.</p>
<hr>
<p>For more verbose output, try this:</p>
<pre><code>unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))
</code></pre>
| 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 containing your package/module, and run the above code before anything is imported. This is often done through a 'sitecustomize.py' file so that it will take effect as soon as the interpreter starts up so you won't need to worry about import ordering.</p>
| 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
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
</code></pre>
<p>Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?</p>
<p>Bonus questions: what would you name the method ? How would you implement it ?</p>
| 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
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
</code></pre>
<p>Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?</p>
<p>Bonus questions: what would you name the method ? How would you implement it ?</p>
| 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 the function too. :-) It's important to recalculate <code>disp</code> every time, in case the daylight-savings value changes or the like. (The conversion back to tuple is required for Jython. CPython doesn't seem to require it.)</p>
<p>This is super ick, because <code>time.gmtime</code> sets the DST flag to false, always. I hate the code, though. There's got to be a better way to do it. And there are probably some corner cases that I haven't got, yet.</p>
| 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
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
</code></pre>
<p>Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?</p>
<p>Bonus questions: what would you name the method ? How would you implement it ?</p>
| 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-python#79913">answer</a>.</p>
| 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
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
</code></pre>
<p>Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?</p>
<p>Bonus questions: what would you name the method ? How would you implement it ?</p>
| 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 following:</p>
<pre><code>>>> time.ctime(time.time())
'Fri Sep 13 12:40:08 2013'
>>> utc_tuple = time.gmtime()
>>> time.ctime(time.mktime(utc_tuple))
'Fri Sep 13 10:40:11 2013'
>>> time.ctime(time.mktime(utc_tuple) - time.timezone)
'Fri Sep 13 12:40:11 2013'
</code></pre>
<p><BR>
Perhaps a more accurate question would be how to <strong>convert a utc_tuple to a local_tuple</strong>.
I would call it <strong>gm_tuple_to_local_tuple</strong> (I prefer long and descriptive names):</p>
<pre><code>>>> time.localtime(time.mktime(utc_tuple) - time.timezone)
time.struct_time(tm_year=2013, tm_mon=9, tm_mday=13, tm_hour=12, tm_min=40, tm_sec=11, tm_wday=4, tm_yday=256, tm_isdst=1)
</code></pre>
<p><BR>
<strong>Validatation:</strong></p>
<pre><code>>>> time.ctime(time.mktime(time.localtime(time.mktime(utc_tuple) - time.timezone)))
'Fri Sep 13 12:40:11 2013'
</code></pre>
<p>Hope this helps,
ilia.</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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 python interpreter can optimize it fairly easily).</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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-11870a08b0fa59a8622201abfac735ea47ffade5" rel="nofollow">Here's just one of many implementations of memoize as a decorator</a>.</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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 the added benefit that expensive(x) may be run <em>less</em> than N times, since any duplicate entries will make use of the memo from the previous execution.</p>
<p>Note that this assumes expensive(x) is a true function, and does not depend on external state that may change. If expensive(x) does depend on external state, and you can detect when that state changes, or you know it <em>wont</em> change during your list comprehension, then you can reset the memos before the comprehension.</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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 more horizontal space, but it's much easier to see what it does at a glance, and you end up not repeating yourself.</p>
| 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 want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
| 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 stage of the pipeline.</li>
<li>Explicit over implicit</li>
<li>Uses generators everywhere until the final step, so no large intermediate lists</li>
</ol>
<p>cf: <a href="http://www.dabeaz.com/generators/" rel="nofollow">'Generator Tricks for System Programmers' by David Beazley</a></p>
| 4 | 2008-09-25T15:12:20Z | [
"python",
"list-comprehension"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.