title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
24,048,447
<p>An attribute of a class instance has 3 properties: the instance, the name of the attribute, and the value of the attribute.</p> <p>In <strong><em>regular attribute access</em></strong>, the instance acts as a dictionary and the name of the attribute acts as the key in that dictionary looking up value.</p> <p><strong>instance(attribute) --> value</strong></p> <p>In <strong><em>__slots__ access</em></strong>, the name of the attribute acts as the dictionary and the instance acts as the key in the dictionary looking up value.</p> <p><strong>attribute(instance) --> value</strong></p> <p>In <strong><em>flyweight pattern</em></strong>, the name of the attribute acts as the dictionary and the value acts as the key in that dictionary looking up the instance.</p> <p><strong>attribute(value) --> instance</strong></p>
1
2014-06-04T22:09:43Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
28,059,785
<blockquote> <h1>In Python, what is the purpose of <code>__slots__</code> and what are the cases one should avoid this?</h1> </blockquote> <h2>TLDR:</h2> <p>The special attribute <code>__slots__</code> allows you to explicitly state in your code which instance attributes you expect your object instances to have, with the expected results:</p> <ol> <li><strong>faster</strong> attribute access.</li> <li>potential <strong>space savings</strong> in memory. </li> </ol> <p>And the biggest caveat for multiple inheritance - multiple "parent classes with nonempty slots" cannot be combined. (Solution? Factor out all but one (or just all) parents' abstraction which they respectively and you collectively will inherit from - giving the abstraction(s) empty slots.)</p> <h3>Requirements:</h3> <ul> <li><p>To have attributes named in <code>__slots__</code> to actually be stored in slots instead of a <code>__dict__</code>, a class must inherit from <code>object</code>.</p></li> <li><p>To prevent the creation of a <code>__dict__</code>, you must inherit from <code>object</code> and all classes in the inheritance must declare <code>__slots__</code> and none of them can have a <code>'__dict__'</code> entry - and they cannot use multiple inheritance. </p></li> </ul> <p>There are a lot of details if you wish to keep reading.</p> <h2>Why use <code>__slots__</code>: Faster attribute access.</h2> <p>The creator of Python, Guido van Rossum, <a href="http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html" rel="nofollow">states</a> that he actually created <code>__slots__</code> for faster attribute access. </p> <p>It is trivial to demonstrate measurably significant faster access:</p> <pre><code>import timeit class Foo(object): __slots__ = 'foo', class Bar(object): pass slotted = Foo() not_slotted = Bar() def get_set_delete_fn(obj): def get_set_delete(): obj.foo = 'foo' obj.foo del obj.foo return get_set_delete </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; min(timeit.repeat(get_set_delete_fn(slotted))) 0.2846834529991611 &gt;&gt;&gt; min(timeit.repeat(get_set_delete_fn(not_slotted))) 0.3664822799983085 </code></pre> <p>The slotted access is almost 30% faster in Python 3.5 on Ubuntu.</p> <pre><code>&gt;&gt;&gt; 0.3664822799983085 / 0.2846834529991611 1.2873325658284342 </code></pre> <p>In Python 2 on Windows I have measured it about 15% faster.</p> <h2>Why use <code>__slots__</code>: Memory Savings</h2> <p>Another purpose of <code>__slots__</code> is to reduce the space in memory that each object instance takes up. </p> <p><a href="https://docs.python.org/2/reference/datamodel.html#slots" rel="nofollow">The documentation clearly states the reasons behind this</a>: </p> <blockquote> <p>By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.</p> <p>The default can be overridden by defining <code>__slots__</code> in a new-style class definition. The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <p><a href="http://docs.sqlalchemy.org/en/rel_1_0/changelog/migration_10.html#significant-improvements-in-structural-memory-use" rel="nofollow">SQLAlchemy attributes</a> a lot of memory savings with <code>__slots__</code>.</p> <p>To verify this, using the Anaconda distribution of Python 2.7 on Ubuntu Linux, with <code>guppy.hpy</code> (aka heapy) and <code>sys.getsizeof</code>, the size of a class instance without <code>__slots__</code> declared, and nothing else, is 64 bytes. That does <em>not</em> include the <code>__dict__</code>. Thank you Python for lazy evaluation again, the <code>__dict__</code> is apparently not called into existence until it is referenced, but classes without data are usually useless. When called into existence, the <code>__dict__</code> attribute is a minimum of 280 bytes additionally. </p> <p>In contrast, a class instance with <code>__slots__</code> declared to be <code>()</code> (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.</p> <p>I tested when my particular implementation of dicts size up by enumerating alphabet characters into a dict, and on the sixth item it climbs to 1048, 22 to 3352, then 85 to 12568 (rather impractical to put that many attributes on a single class, probably violating the single responsibility principle there.)</p> <pre><code>attrs __slots__ no slots declared + __dict__ none 16 64 (+ 280 if __dict__ referenced) one 56 64 + 280 two 64 64 + 280 six 96 64 + 1048 22 224 64 + 3352 </code></pre> <p>So we see how nicely <code>__slots__</code> scale for instances to save us memory, and that is the reason you would want to use <code>__slots__</code>. </p> <h2>Demonstration of <code>__slots__</code>:</h2> <p>To prevent the creation of a <code>__dict__</code>, you must subclass <code>object</code>:</p> <pre><code>&gt;&gt;&gt; class Base(object): __slots__ = () &gt;&gt;&gt; b = Base() &gt;&gt;&gt; b.a = 'a' Traceback (most recent call last): File "&lt;pyshell#38&gt;", line 1, in &lt;module&gt; b.a = 'a' AttributeError: 'Base' object has no attribute 'a' </code></pre> <p>Or another class that defines <code>__slots__</code></p> <pre><code>&gt;&gt;&gt; class Child(Base): __slots__ = ('a',) &gt;&gt;&gt; c = Child() &gt;&gt;&gt; c.a = 'a' &gt;&gt;&gt; c.b = 'b' Traceback (most recent call last): File "&lt;pyshell#42&gt;", line 1, in &lt;module&gt; c.b = 'b' AttributeError: 'Child' object has no attribute 'b' </code></pre> <p>To allow <code>__dict__</code> creation while subclassing slotted objects, just add <code>'__dict__'</code> to the <code>__slots__</code>:</p> <pre><code>&gt;&gt;&gt; class SlottedWithDict(Child): __slots__ = ('__dict__', 'b') &gt;&gt;&gt; swd = SlottedWithDict() &gt;&gt;&gt; swd.a = 'a' &gt;&gt;&gt; swd.b = 'b' &gt;&gt;&gt; swd.c = 'c' &gt;&gt;&gt; swd.__dict__ {'c': 'c'} </code></pre> <p>Or you don't even need to declare <strong>slots</strong> in your subclass, and you will still use slots from the parents, but not restrict the creation of a <code>__dict__</code>:</p> <pre><code>&gt;&gt;&gt; class NoSlots(Child): pass &gt;&gt;&gt; ns = NoSlots() &gt;&gt;&gt; ns.a = 'a' &gt;&gt;&gt; ns.b = 'b' &gt;&gt;&gt; ns.__dict__ {'b': 'b'} </code></pre> <p>However, <code>__slots__</code> may cause problems for multiple inheritance:</p> <pre><code>&gt;&gt;&gt; class BaseA(object): __slots__ = ('a',) &gt;&gt;&gt; class BaseB(object): __slots__ = ('b',) &gt;&gt;&gt; class Child(BaseA, BaseB): __slots__ = () Traceback (most recent call last): File "&lt;pyshell#68&gt;", line 1, in &lt;module&gt; class Child(BaseA, BaseB): __slots__ = () TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict </code></pre> <p>If you run into this problem, just remove <code>__slots__</code>, and put it back in where you have a lot of instances.</p> <pre><code>&gt;&gt;&gt; class BaseA(object): __slots__ = () &gt;&gt;&gt; class BaseB(object): __slots__ = () &gt;&gt;&gt; class Child(BaseA, BaseB): __slots__ = ('a', 'b') &gt;&gt;&gt; c = Child &gt;&gt;&gt; c.a = 'a' &gt;&gt;&gt; c.b = 'b' &gt;&gt;&gt; c.c = 'c' &gt;&gt;&gt; c.__dict__ &lt;dictproxy object at 0x10C944B0&gt; &gt;&gt;&gt; c.__dict__['c'] 'c' </code></pre> <h3>Add <code>'__dict__'</code> to <code>__slots__</code> to get dynamic assignment:</h3> <pre><code>class Foo(object): __slots__ = 'bar', 'baz', '__dict__' </code></pre> <p>and now:</p> <pre><code>&gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; foo.boink = 'boink' </code></pre> <p>So with <code>'__dict__'</code> in slots we lose some of the size benefits with the upside of having dynamic assignment and still having slots for the names we do expect.</p> <p>When you inherit from an object that isn't slotted, you get the same sort of semantics when you use <code>__slots__</code> - names that are in <code>__slots__</code> point to slotted values, while any other values are put in the instance's <code>__dict__</code>.</p> <p>Avoiding <code>__slots__</code> because you want to be able to add attributes on the fly is actually not a good reason - just add <code>"__dict__"</code> to your <code>__slots__</code> if this is required.</p> <h3>Set to empty tuple when subclassing a namedtuple:</h3> <p>The namedtuple builtin make immutable instances that are very lightweight (essentially, the size of tuples) but to get the benefits, you need to do it yourself if you subclass them:</p> <pre><code>from collections import namedtuple class MyNT(namedtuple('MyNT', 'bar baz')): """MyNT is an immutable and lightweight object""" __slots__ = () </code></pre> <p>usage:</p> <pre><code>&gt;&gt;&gt; nt = MyNT('bar', 'baz') &gt;&gt;&gt; nt.bar 'bar' &gt;&gt;&gt; nt.baz 'baz' </code></pre> <h2>Biggest Caveat: Multiple inheritance</h2> <p>Even when non-empty slots are the same for multiple parents, they cannot be used together:</p> <pre><code>&gt;&gt;&gt; class Foo(object): __slots__ = 'foo', 'bar' &gt;&gt;&gt; class Bar(object): __slots__ = 'foo', 'bar' # alas, would work if empty, i.e. () &gt;&gt;&gt; class Baz(Foo, Bar): pass Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict </code></pre> <p>Using an empty <code>__slots__</code> in the parent seems to provide the most flexibility, <strong>allowing the child to choose to prevent or allow</strong> (by adding <code>'__dict__'</code> to get dynamic assignment, see section above) <strong>the creation of a dict</strong>:</p> <pre><code>&gt;&gt;&gt; class Foo(object): __slots__ = () &gt;&gt;&gt; class Bar(object): __slots__ = () &gt;&gt;&gt; class Baz(Foo, Bar): __slots__ = ('foo', 'bar') &gt;&gt;&gt; b = Baz() &gt;&gt;&gt; b.foo, b.bar = 'foo', 'bar' </code></pre> <p>You don't <em>have</em> to have slots - so if you add them, and remove them later, it shouldn't cause any problems.</p> <p><strong>Going out on a limb here</strong>: If you're composing <a href="http://stackoverflow.com/questions/860245/mixin-vs-inheritance/27907511#27907511">mixins</a> or using <a href="http://stackoverflow.com/questions/372042/difference-between-abstract-class-and-interface-in-python/31439126#31439126">abstract base classes</a>, which aren't intended to be instantiated, an empty <code>__slots__</code> in those parents seems to be the best way to go in terms of flexibility for subclassers.</p> <h2>Other cases to avoid slots:</h2> <ul> <li>Avoid them when you want to perform <code>__class__</code> assignment with another class that doesn't have them (and you can't add them).</li> <li>Avoid them if you want to subclass variable length builtins like long, tuple, or str, and you want to add attributes to them.</li> <li>Avoid them if you insist on providing default values via class attributes for instance variables. </li> <li>Avoid them for parent classes in the case of multiple inheritance - you can reinsert them for a child where you have a lot of instances (see previous section for recommendation).</li> </ul> <p>You may be able to tease out further caveats from the rest of the <code>__slots__</code> <a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="nofollow">documentation</a>, which follows:</p> <blockquote> <p><strong><code>__slots__</code></strong></p> <blockquote> <p>This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. If defined in a new-style class, <code>__slots__</code> reserves space for the declared variables and prevents the automatic creation of <code>__dict__</code> and <code>__weakref__</code> for each instance.</p> </blockquote> <p>Notes on using <code>__slots__</code></p> <ul> <li><p>When inheriting from a class without <code>__slots__</code>, the <code>__dict__</code> attribute of that class will always be accessible, so a <code>__slots__</code> definition in the subclass is meaningless.</p></li> <li><p>Without a <code>__dict__</code> variable, instances cannot be assigned new variables not listed in the <code>__slots__</code> definition. Attempts to assign to an unlisted variable name raises <code>AttributeError</code>. If dynamic assignment of new variables is desired, then add <code>'__dict__'</code> to the sequence of strings in the <code>__slots__</code> declaration.</p> <p><em>Changed in version 2.3:</em> Previously, adding <code>'__dict__'</code> to the <code>__slots__</code> declaration would not enable the assignment of new attributes not specifically listed in the sequence of instance variable names.</p></li> <li><p>Without a <code>__weakref__</code> variable for each instance, classes defining <code>__slots__</code> do not support weak references to its instances. If weak reference support is needed, then add <code>'__weakref__'</code> to the sequence of strings in the <code>__slots__</code> declaration.</p> <p><em>Changed in version 2.3:</em> Previously, adding <code>'__weakref__'</code> to the <code>__slots__</code> declaration would not enable support for weak references.</p></li> <li><p><code>__slots__</code> are implemented at the class level by creating descriptors (<a href="https://docs.python.org/2/reference/datamodel.html#implementing-descriptors" rel="nofollow">Implementing Descriptors</a>) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by <code>__slots__</code>; otherwise, the class attribute would overwrite the descriptor assignment.</p></li> <li><p>The action of a <code>__slots__</code> declaration is limited to the class where it is defined. As a result, subclasses will have a <code>__dict__</code> unless they also define <code>__slots__</code> (which must only contain names of any additional slots).</p></li> <li><p>If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this.</p></li> <li><p>Nonempty <code>__slots__</code> does not work for classes derived from “variable-length” built-in types such as long, str and tuple.</p></li> <li><p>Any non-string iterable may be assigned to <code>__slots__</code>. Mappings may also be used; however, in the future, special meaning may be assigned to the values corresponding to each key.</p></li> <li><p><code>__class__</code> assignment works only if both classes have the same <code>__slots__</code>.</p> <p><em>Changed in version 2.6:</em> Previously, <code>__class__</code> assignment raised an error if either new or old class had <code>__slots__</code>.</p></li> </ul> </blockquote> <h2>Critiques of other answers</h2> <p>The current top answers cite outdated information and are quite hand-wavy and miss the mark in some important ways.</p> <h3>Pickling, <code>__slots__</code> doesn't break</h3> <p>When pickling a slotted object, you may find it complains with a misleading <code>TypeError</code>: </p> <pre><code>&gt;&gt;&gt; pickle.loads(pickle.dumps(f)) TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled </code></pre> <p>This is actually incorrect. This message comes from the oldest protocol, which is the default. You can select the latest protocol with the <code>-1</code> argument. In Python 2.7 this would be <code>2</code> (which was introduced in 2.3), and in 3.6 it is <code>4</code>.</p> <pre><code>&gt;&gt;&gt; pickle.loads(pickle.dumps(f, -1)) &lt;__main__.Foo object at 0x1129C770&gt; </code></pre> <p>in Python 2.7:</p> <pre><code>&gt;&gt;&gt; pickle.loads(pickle.dumps(f, 2)) &lt;__main__.Foo object at 0x1129C770&gt; </code></pre> <p>in Python 3.6</p> <pre><code>&gt;&gt;&gt; pickle.loads(pickle.dumps(f, 4)) &lt;__main__.Foo object at 0x1129C770&gt; </code></pre> <p>So I would keep this in mind, as it is a solved problem.</p> <h2>Critique of the (until Oct 2, 2016) accepted answer</h2> <p>The first paragraph is half short explanation, half predictive. Here's the only part that actually answers the question</p> <blockquote> <p>The proper use of <code>__slots__</code> is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots</p> </blockquote> <p>The second half is wishful thinking, and off the mark:</p> <blockquote> <p>While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.</p> </blockquote> <p>Python actually does something similar to this, only creating the <code>__dict__</code> when it is accessed, but creating lots of objects with no data is fairly ridiculous.</p> <p>The second paragraph oversimplifies and misses actual reasons to avoid <code>__slots__</code>. The below is <em>not</em> a real reason to avoid slots (for <em>actual</em> reasons, see the rest of my answer above.):</p> <blockquote> <p>They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies.</p> </blockquote> <p>It then goes on to discuss other ways of accomplishing that perverse goal with Python, not discussing anything to do with <code>__slots__</code>.</p> <p>The third paragraph is more wishful thinking. Together it is mostly off-the-mark content that the answerer didn't even author and contributes to ammunition for critics of the site.</p> <h1>Memory usage evidence</h1> <p>Create some normal objects and slotted objects:</p> <pre><code>&gt;&gt;&gt; class Foo(object): pass &gt;&gt;&gt; class Bar(object): __slots__ = () </code></pre> <p>Instantiate a million of them:</p> <pre><code>&gt;&gt;&gt; foos = [Foo() for f in xrange(1000000)] &gt;&gt;&gt; bars = [Bar() for b in xrange(1000000)] </code></pre> <p>Inspect with <code>guppy.hpy().heap()</code>:</p> <pre><code>&gt;&gt;&gt; guppy.hpy().heap() Partition of a set of 2028259 objects. Total size = 99763360 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 1000000 49 64000000 64 64000000 64 __main__.Foo 1 169 0 16281480 16 80281480 80 list 2 1000000 49 16000000 16 96281480 97 __main__.Bar 3 12284 1 987472 1 97268952 97 str ... </code></pre> <p>Access the regular objects and their <code>__dict__</code> and inspect again:</p> <pre><code>&gt;&gt;&gt; for f in foos: ... f.__dict__ &gt;&gt;&gt; guppy.hpy().heap() Partition of a set of 3028258 objects. Total size = 379763480 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 1000000 33 280000000 74 280000000 74 dict of __main__.Foo 1 1000000 33 64000000 17 344000000 91 __main__.Foo 2 169 0 16281480 4 360281480 95 list 3 1000000 33 16000000 4 376281480 99 __main__.Bar 4 12284 0 987472 0 377268952 99 str ... </code></pre> <p>This is consistent with the history of Python, from <a href="https://www.python.org/download/releases/2.2.2/descrintro/" rel="nofollow">Unifying types and classes in Python 2.2</a></p> <blockquote> <p>If you subclass a built-in type, extra space is automatically added to the instances to accomodate <code>__dict__</code> and <code>__weakrefs__</code>. (The <code>__dict__</code> is not initialized until you use it though, so you shouldn't worry about the space occupied by an empty dictionary for each instance you create.) If you don't need this extra space, you can add the phrase "<code>__slots__ = []</code>" to your class.</p> </blockquote>
119
2015-01-21T04:46:42Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
30,613,834
<p>In addition to the other answers, here is an example of using <code>__slots__</code>:</p> <pre><code>&gt;&gt;&gt; class Test(object): #Must be new-style class! ... __slots__ = ['x', 'y'] ... &gt;&gt;&gt; pt = Test() &gt;&gt;&gt; dir(pt) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__slots__', '__str__', 'x', 'y'] &gt;&gt;&gt; pt.x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: x &gt;&gt;&gt; pt.x = 1 &gt;&gt;&gt; pt.x 1 &gt;&gt;&gt; pt.z = 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Test' object has no attribute 'z' &gt;&gt;&gt; pt.__dict__ Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Test' object has no attribute '__dict__' &gt;&gt;&gt; pt.__slots__ ['x', 'y'] </code></pre> <p>So, to implement <code>__slots__</code>, it only takes an extra line (and making your class a new-style class if it isn't already). This way you can <a href="http://dev.svetlyak.ru/using-slots-for-optimisation-in-python-en/">reduce the memory footprint of those classes 5-fold</a>, at the expense of having to write custom pickle code, if and when that becomes necessary.</p>
13
2015-06-03T07:43:05Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
34,751,434
<p>The original question was about general use cases not only about memory. So it should be mentioned here that you also get better <em>performance</em> when instantiating large amounts of objects - interesting e.g. when parsing large documents into objects or from a database.</p> <p>Here is a comparison of creating object trees with a million entries, using slots and without slots. As a reference also the performance when using plain dicts for the trees (Py2.7.10 on OSX):</p> <pre><code>********** RUN 1 ********** 1.96036410332 &lt;class 'css_tree_select.element.Element'&gt; 3.02922606468 &lt;class 'css_tree_select.element.ElementNoSlots'&gt; 2.90828204155 dict ********** RUN 2 ********** 1.77050495148 &lt;class 'css_tree_select.element.Element'&gt; 3.10655999184 &lt;class 'css_tree_select.element.ElementNoSlots'&gt; 2.84120798111 dict ********** RUN 3 ********** 1.84069895744 &lt;class 'css_tree_select.element.Element'&gt; 3.21540498734 &lt;class 'css_tree_select.element.ElementNoSlots'&gt; 2.59615707397 dict ********** RUN 4 ********** 1.75041103363 &lt;class 'css_tree_select.element.Element'&gt; 3.17366290092 &lt;class 'css_tree_select.element.ElementNoSlots'&gt; 2.70941114426 dict </code></pre> <p>Test classes (ident, appart from slots):</p> <pre><code>class Element(object): __slots__ = ['_typ', 'id', 'parent', 'childs'] def __init__(self, typ, id, parent=None): self._typ = typ self.id = id self.childs = [] if parent: self.parent = parent parent.childs.append(self) class ElementNoSlots(object): (same, w/o slots) </code></pre> <p>testcode, verbose mode:</p> <pre><code>na, nb, nc = 100, 100, 100 for i in (1, 2, 3, 4): print '*' * 10, 'RUN', i, '*' * 10 # tree with slot and no slot: for cls in Element, ElementNoSlots: t1 = time.time() root = cls('root', 'root') for i in xrange(na): ela = cls(typ='a', id=i, parent=root) for j in xrange(nb): elb = cls(typ='b', id=(i, j), parent=ela) for k in xrange(nc): elc = cls(typ='c', id=(i, j, k), parent=elb) to = time.time() - t1 print to, cls del root # ref: tree with dicts only: t1 = time.time() droot = {'childs': []} for i in xrange(na): ela = {'typ': 'a', id: i, 'childs': []} droot['childs'].append(ela) for j in xrange(nb): elb = {'typ': 'b', id: (i, j), 'childs': []} ela['childs'].append(elb) for k in xrange(nc): elc = {'typ': 'c', id: (i, j, k), 'childs': []} elb['childs'].append(elc) td = time.time() - t1 print td, 'dict' del droot </code></pre>
0
2016-01-12T18:42:31Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
39,042,400
<p>A very simple example of <code>__slot__</code> attribute.</p> <h2>Problem: Without <code>__slots__</code></h2> <p>If I don't have <code>__slot__</code> attribute in my class, I can add new attributes to my objects. </p> <pre><code>class Test: pass obj1=Test() obj2=Test() print(obj1.__dict__) #--&gt; {} obj1.x=12 print(obj1.__dict__) # --&gt; {'x': 12} obj1.y=20 print(obj1.__dict__) # --&gt; {'x': 12, 'y': 20} obj2.x=99 print(obj2.__dict__) # --&gt; {'x': 99} </code></pre> <p>If you look at example above, you can see that <strong>obj1</strong> and <strong>obj2</strong> have their own <strong>x</strong> and <strong>y</strong> attributes and python has also created a <code>dict</code> attribute for each object (<strong>obj1</strong> and <strong>obj2</strong>).</p> <p>Suppose if my class <strong>Test</strong> has thousands of such objects? Creating an additional attribute <code>dict</code> for each object will cause lot of overhead (memory, computing power etc.) in my code. </p> <h2>Solution: With <code>__slots__</code></h2> <p>Now in the following example my class <strong>Test</strong> contains <code>__slots__</code> attribute. Now I can't add new attributes to my objects (except attribute <code>x</code>) and python doesn't create <code>dict</code> attribute anymore. This can saves lot of overhead.</p> <pre><code>class Test: __slots__=("x") obj1=Test() obj2=Test() obj1.x=12 print(obj1.x) # --&gt; 12 obj2.x=99 print(obj2.x) # --&gt; 99 obj1.y=28 print(obj1.y) # --&gt; AttributeError: 'Test' object has no attribute 'y' </code></pre>
0
2016-08-19T15:09:23Z
[ "python" ]
Incorrect answer in dll import in Python
472,170
<p>In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success message. Otherwise, get updated with error message.</p> <p>When my script receives the integer, I should print the message in the second variable. I'm not able to do that.</p>
-4
2009-01-23T07:18:32Z
472,186
<p>Python does not support the concept of passing a string "by reference" in the same way that VB.NET does. So it might not be possible to do this without some more work.</p> <p>However, without seeing your code it's definitely not possible to tell you what's wrong.</p>
1
2009-01-23T07:26:34Z
[ "python", "import" ]
Incorrect answer in dll import in Python
472,170
<p>In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success message. Otherwise, get updated with error message.</p> <p>When my script receives the integer, I should print the message in the second variable. I'm not able to do that.</p>
-4
2009-01-23T07:18:32Z
472,475
<p>Python strings are immutable. There is no way the string can be changed inside the function.</p> <p>So what you really want is to pass a <em>char buffer</em> of some sort. You can create those in python using the <code>ctypes</code> module. </p> <p>Please edit the question and paste a minimal snippet of the code so we can test and give more information.</p>
3
2009-01-23T10:31:32Z
[ "python", "import" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
472,243
<p>There are several solutions (by default, they are dropped). Here is an example using the option HEADERFUNCTION which lets you indicate a function to handle them.</p> <p>Other solutions are options WRITEHEADER (not compatible with WRITEFUNCTION) or setting HEADER to True so that they are transmitted with the body.</p> <pre><code>#!/usr/bin/python import pycurl import sys class Storage: def __init__(self): self.contents = '' self.line = 0 def store(self, buf): self.line = self.line + 1 self.contents = "%s%i: %s" % (self.contents, self.line, buf) def __str__(self): return self.contents retrieved_body = Storage() retrieved_headers = Storage() c = pycurl.Curl() c.setopt(c.URL, 'http://www.demaziere.fr/eve/') c.setopt(c.WRITEFUNCTION, retrieved_body.store) c.setopt(c.HEADERFUNCTION, retrieved_headers.store) c.perform() c.close() print retrieved_headers print retrieved_body </code></pre>
22
2009-01-23T08:13:57Z
[ "python", "curl", "pycurl" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
472,345
<p>This might or might not be an alternative for you:</p> <pre><code>import urllib headers = urllib.urlopen('http://www.pythonchallenge.com').headers.headers </code></pre>
1
2009-01-23T09:26:00Z
[ "python", "curl", "pycurl" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
7,269,900
<p>Anothr alternate, human_curl usage: pip human_curl</p> <pre><code>In [1]: import human_curl as hurl In [2]: r = hurl.get("http://stackoverflow.com") In [3]: r.headers Out[3]: {'cache-control': 'public, max-age=45', 'content-length': '198515', 'content-type': 'text/html; charset=utf-8', 'date': 'Thu, 01 Sep 2011 11:53:43 GMT', 'expires': 'Thu, 01 Sep 2011 11:54:28 GMT', 'last-modified': 'Thu, 01 Sep 2011 11:53:28 GMT', 'vary': '*'} </code></pre>
5
2011-09-01T11:54:40Z
[ "python", "curl", "pycurl" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
21,566,886
<pre><code>import pycurl from StringIO import StringIO headers = StringIO() c = pycurl.Curl() c.setopt(c.URL, url) c.setopt(c.HEADER, 1) c.setopt(c.NOBODY, 1) # header only, no body c.setopt(c.HEADERFUNCTION, headers.write) c.perform() print headers.getvalue() </code></pre> <p>Add any other curl setopts as necessary/desired, such as FOLLOWLOCATION.</p>
4
2014-02-05T01:20:49Z
[ "python", "curl", "pycurl" ]
How to specify uniqueness for a tuple of field in a Django model
472,392
<p>Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field?</p> <p>Or do I need to check this constraint in the clean() method?</p>
15
2009-01-23T09:50:59Z
472,688
<p>There is a META option called unique_together. For example:</p> <pre><code>class MyModel(models.Model): field1 = models.BlahField() field2 = models.FooField() field3 = models.BazField() class Meta: unique_together = ("field1", "field2") </code></pre> <p>More info on the Django <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together">documentation</a> page.</p>
31
2009-01-23T12:16:04Z
[ "python", "django", "django-models" ]
TypeError: 'tuple' object is not callable
472,503
<p>I was doing the tutorial from the book teach yourself django in 24 hours and in part1 hour 4 i got stuck on this error. </p> <pre><code>Traceback (most recent call last): File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 278, in run self.result = application(self.environ, self.start_response) File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 635, in __call__ return self.application(environ, start_response) File "C:\Python25\lib\site-packages\django\core\handlers\wsgi.py", line 239, in __call__ response = self.get_response(request) File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 67, in get_response response = middleware_method(request) File "C:\Python25\Lib\site-packages\django\middleware\common.py", line 56, in process_request if (not _is_valid_path(request.path_info) and File "C:\Python25\Lib\site-packages\django\middleware\common.py", line 142, in _is_valid_path urlresolvers.resolve(path) File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 254, in resolve return get_resolver(urlconf).resolve(path) File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 181, in resolve for pattern in self.url_patterns: File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 205, in _get_url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 200, in _get_urlconf_module self._urlconf_module = __import__(self.urlconf_name, {}, {}, ['']) File "c:\projects\iFriends\..\iFriends\urls.py", line 17, in &lt;module&gt; (r'^admin/', include('django.contribute.admin.urls')) TypeError: 'tuple' object is not callable </code></pre> <p>Can someone help me please..</p> <p>url.py</p> <pre><code>from django.conf.urls.defaults import * ####Uncomment the next two lines to enable the admin: #### from django.contrib import admin #### admin.autodiscover() urlpatterns = patterns('', (r'^People/$', 'iFriends.People.views.index') , (r'^admin/', include('django.contrib.admin.urls')), # Example: # (r'^iFriends/', include('iFriends.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: ) </code></pre>
0
2009-01-23T10:42:44Z
472,515
<p>You somehow set some function to a tuple. Please edit the question and paste your <code>urls.py</code> code, so we can point you to the error.</p> <p>I can try a <strong>wild guess</strong>:</p> <pre><code>File "c:\projects\iFriends\..\iFriends\urls.py", line 17, in &lt;module&gt; (r'^admin/', include('django.contribute.admin.urls')) </code></pre> <p>This somehow tells me that you missed a comma on line 16, so:</p> <pre><code>16. (r'^/', 'some_stuff....') # &lt;-- missed comma here 17. (r'^admin/', include('django.contribute.admin.urls')) </code></pre> <p>Just put the comma and it will work. If that's not the case, I'll send my cristal ball for mainantance. Paste the code.</p> <h1>EDIT</h1> <p>Seems like you have pasted the <code>urls.py</code> as an answer. Please edit the <strong>question</strong> and paste urls.py there.</p> <p>Anyway, the error has changed. What did you do? In this new error, <code>urls.py</code> is not found anymore so maybe you've renamed it? Have you changed the way you run the application?</p> <p>The file you pasted <strong>is not</strong> the one that is running. Are you pasting <code>url.py</code> and django is reading <code>urls.py</code>? The code in the error doesn't match the code you pasted! Please paste the correct file, i.e. the same that gives the error, or we can't help.</p>
20
2009-01-23T10:47:45Z
[ "python", "django" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
472,588
<p>Simple approach:</p> <pre><code>print (name for name in ('bob', 'fred') if name == 'bob').next() </code></pre> <p>If you really want an error when there is more than one value, then you need a function. The most simple I can think of is (<strong>EDITED</strong> to work with lists too):</p> <pre><code>def one(iterable): it = iter(iterable) val = it.next() try: it.next() except StopIteration: return val else: raise Exception('More than one value') </code></pre>
3
2009-01-23T11:23:12Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
472,646
<p>Have a look into the <a href="http://docs.python.org/library/itertools.html#itertools.islice" rel="nofollow">itertools.islice()</a> method.</p> <pre><code>&gt;&gt;&gt; i2=itertools.islice((name for name in ('bob','fred') if name=='bob'),0,1,1) &gt;&gt;&gt; i2.next() 'bob' &gt;&gt;&gt; i2.next() Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; </code></pre> <blockquote> <p>This module implements a number of iterator building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python.</p> <p>The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Standardization helps avoid the readability and reliability problems which arise when many different individuals create their own slightly varying implementations, each with their own quirks and naming conventions.</p> <p>The tools are designed to combine readily with one another. This makes it easy to construct more specialized tools succinctly and efficiently in pure Python.</p> </blockquote>
1
2009-01-23T11:54:31Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
472,653
<p>Do you mean?</p> <pre><code>def one( someGenerator ): if len(list(someGenerator)) != 1: raise Exception( "Not a Singleton" ) </code></pre> <p>What are you trying to accomplish with all the extra code? </p>
3
2009-01-23T12:00:45Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
472,826
<p>Here is my try at the <code>one()</code> function. I would avoid the explicit <code>.next()</code> call and use a for loop instead.</p> <pre><code>def one(seq): counter = 0 for elem in seq: result = elem counter += 1 if counter &gt; 1: break if counter == 0: raise Exception('No values') elif counter &gt; 1: raise Exception('Too many values') return result </code></pre>
1
2009-01-23T13:13:41Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
473,042
<p>First, (to answer the actual question!) your solution will work fine as will the other variants proposed.</p> <p>I would add that in this case, IMO, generators are overly complicated. If you expect to have one value, you'll probably never have enough for memory usage to be a concern, so I would have just used the obvious and much clearer:</p> <pre><code>children = [name for name in ('bob','fred') if name=='bob'] if len(children) == 0: raise Exception('No values') elif len(children) &gt; 1: raise Exception('Too many values') else: child = children[0] </code></pre>
1
2009-01-23T14:21:15Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
473,337
<p>A simpler solution is to use tuple unpacking. This will already do everything you want, including checking that it contains exactly one item.</p> <p>Single item:</p> <pre><code> &gt;&gt;&gt; name, = (name for name in ('bob','fred') if name=='bob') &gt;&gt;&gt; name 'bob' </code></pre> <p>Too many items:</p> <pre><code>&gt;&gt;&gt; name, = (name for name in ('bob','bob') if name=='bob') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: too many values to unpack </code></pre> <p>No items:</p> <pre><code>&gt;&gt;&gt; name, = (name for name in ('fred','joe') if name=='bob') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: need more than 0 values to unpack </code></pre>
12
2009-01-23T15:35:10Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') </code></pre>
2
2009-01-23T11:16:35Z
1,212,394
<p>How about using Python's for .. in syntax with a counter? Similar to unbeknown's answer.</p> <pre><code>def one(items): count = 0 value = None for item in items: if count: raise Exception('Too many values') count += 1 value = item if not count: raise Exception('No values') return value </code></pre>
0
2009-07-31T12:56:56Z
[ "python", "iterator", "generator" ]
Subtract from an input appended list with a running balance output
472,839
<p><em>Noob</em></p> <p>I am trying to write a script that gives a running balance. I am messing up on the elementary declared functions of python.</p> <p>I need it too:</p> <ul> <li>accept a balance via input</li> <li>append a list of transactions </li> <li>take those out one by one in the order they were input </li> <li>print a running total </li> <li>use <a href="http://www.pasko.net/PyHtmlTable/" rel="nofollow">pyhtmltable</a> to make the output in html table ready form for copy and pasting</li> </ul> <p>Code:</p> <pre><code># transaction posting on available balance import PyHtmlTable import twodarr import string,re import copy import sys posting_trans = [] #creating a list of posting debits here avail_bal = int(input('What is the balance available to pay transactions?')) #getting the starting balance while True: #building up the list of transactions ans = input('Please enter the debits in order of posting one at a time. If there is no more, please enter 0:') if int(ans) == 0: break if ans &gt; 0: # to get out of loop posting_trans.append(ans) num_trans = int(len(posting_trans)) #counting the number of transactions print "&lt;b&gt; Beginning available balance of",avail_bal," &lt;/b&gt; " # start of the html table tabledict = {'width':'400','border':2,'bgcolor':'white'} t = PyHtmlTable.PyHtmlTable( 2, 1 , tabledict ) t.setCellcontents(0,0,"Transactions") #header cells t.setCellcontents(1,0,"Available Balance") while True: #trying to create the rest of a dynamic table if countdown == 0: break for countdown in range(1,num_trans): t.add_row(1) def newer_bal(): newer_bal(avail_bal - posting_trans[countdown]) t.setCellcontents(0, 1, posting_trans[countdown]) t.setCellcontents(1, 1, newer_bal) t.display() </code></pre>
0
2009-01-23T13:17:23Z
472,908
<p>Something like that?</p> <pre><code># transaction posting on available balance import PyHtmlTable posting_trans = [] #creating a list of posting debits here #getting the starting balance print 'What is the balance available to pay transactions? ' avail_bal = float(raw_input('Value: ')) while True: #building up the list of transactions print 'Please enter the debits in order of posting one at a time.' print 'If there is no more, please enter 0:' ans = float(raw_input('Value: ')) if ans == 0: break # to get out of loop posting_trans.append(ans) # start of the html table print "&lt;b&gt; Beginning available balance of %.2f&lt;/b&gt;" % avail_bal tabledict = {'width': '400', 'border': 2, 'bgcolor': 'white'} t = PyHtmlTable.PyHtmlTable(2, 1, tabledict) t.setCellcontents(0, 0, "Transaction Value") #header cells t.setCellcontents(0, 1, "Available Balance") for line, trans in enumerate(posting_trans): avail_bal -= trans t.setCellcontents(line + 1, 0, '%.2f' % trans) t.setCellcontents(line + 1, 1, '%.2f' % avail_bal) t.display() </code></pre> <p>Hints:</p> <ul> <li>Don't use <code>input()</code>. Use <code>raw_input()</code> instead. It has been renamed to <code>input()</code> in python 3.0.</li> <li>You don't need to store the values in the list. You could store them in the table already, that is the point into using <code>PyHtmlTable</code>. I left the list for didactic purposes.</li> <li>Read a tutorial. Read documentation. Write lots of code.</li> </ul>
2
2009-01-23T13:40:12Z
[ "python", "loops", "running-balance" ]
Binary data with pyserial(python serial port)
472,977
<p>serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?</p> <p>I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem. </p>
15
2009-01-23T14:02:43Z
473,057
<p>You need to convert your data to a string</p> <pre><code>"\xc0\x04\x00" </code></pre> <p>Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte <code>"\x00"</code>.</p> <p>One way to do this:</p> <pre><code>&gt;&gt;&gt; import array &gt;&gt;&gt; array.array('B', [0xc0, 0x04, 0x00]).tostring() '\xc0\x04\x00' </code></pre>
9
2009-01-23T14:25:28Z
[ "python", "binary", "serial-port", "pyserial" ]
Binary data with pyserial(python serial port)
472,977
<p>serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?</p> <p>I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem. </p>
15
2009-01-23T14:02:43Z
1,281,992
<p>An alternative method, without using the <code>array</code> module:</p> <pre><code>def a2s(arr): """ Array of integer byte values --&gt; binary string """ return ''.join(chr(b) for b in arr) </code></pre>
12
2009-08-15T14:19:51Z
[ "python", "binary", "serial-port", "pyserial" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
473,108
<p>You are looking for <a href="http://docs.python.org/library/collections.html#defaultdict"><code>collections.defaultdict</code></a> (available for Python 2.5+). This</p> <pre><code>from collections import defaultdict my_dict = defaultdict(int) my_dict[key] += 1 </code></pre> <p>will do what you want.</p> <p>For regular Python <code>dict</code>s, if there is no value for a given key, you will <em>not</em> get <code>None</code> when accessing the dict -- a <code>KeyError</code> will be raised. So if you want to use a regular <code>dict</code>, instead of your code you would use</p> <pre><code>if key in my_dict: my_dict[key] += 1 else: my_dict[key] = 1 </code></pre>
182
2009-01-23T14:38:49Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
473,114
<p>You need the <code>key in dict</code> idiom for that.</p> <pre><code>if key in my_dict and not (my_dict[key] is None): # do something else: # do something else </code></pre> <p>However, you should probably consider using <code>defaultdict</code> (as dF suggested).</p>
41
2009-01-23T14:41:38Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
473,184
<p>The way you are trying to do it is called LBYL (look before you leap), since you are checking conditions before trying to increment your value.</p> <p>The other approach is called EAFP (easier to ask forgiveness then permission). In that case, you would just try the operation (increment the value). If it fails, you catch the exception and set the value to 1. This is a slightly more Pythonic way to do it (IMO).</p> <p><a href="http://mail.python.org/pipermail/python-list/2003-May/205182.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2003-May/205182.html</a></p>
4
2009-01-23T15:00:45Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
473,227
<p>Agreed with cgoldberg. How I do it is:</p> <pre><code>try: dict[key] += 1 except KeyError: dict[key] = 1 </code></pre> <p>So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.</p>
8
2009-01-23T15:09:59Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
473,344
<p>I prefer to do this in one line of code.</p> <pre> my_dict = {} my_dict[some_key] = my_dict.get(some_key, 0) + 1 </pre> <p>Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere.</p>
152
2009-01-23T15:39:05Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
473,501
<p>As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has_key() method:</p> <pre><code>my_dict = {} def add (key): if my_dict.has_key(key): my_dict[key] += 1 else: my_dict[key] = 1 if __name__ == '__main__': add("foo") add("bar") add("foo") print my_dict </code></pre>
10
2009-01-23T16:17:20Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
2,198,921
<p>To answer the question "<em>how can I find out if a given index in that dict has already been set to a non-None value</em>", I would prefer this:</p> <pre><code>try: nonNone = my_dict[key] is not None except KeyError: nonNone = False </code></pre> <p>This conforms to the already invoked concept of EAFP (easier to ask forgiveness then permission). It also avoids the duplicate key lookup in the dictionary as it would in <code>key in my_dict and my_dict[key] is not None</code> what is interesting if lookup is expensive.</p> <p>For the actual <em>problem</em> that you have posed, i.e. incrementing an int if it exists, or setting it to a default value otherwise, I also recommend the</p> <pre><code>my_dict[key] = my_dict.get(key, default) + 1 </code></pre> <p>as in the answer of Andrew Wilkinson.</p> <p>There is a third solution if you are storing modifyable objects in your dictionary. A common example for this is a <a href="http://en.wikipedia.org/wiki/Multimap">multimap</a>, where you store a list of elements for your keys. In that case, you can use:</p> <pre><code>my_dict.setdefault(key, []).append(item) </code></pre> <p>If a value for key does not exist in the dictionary, the setdefault method will set it to the second parameter of setdefault. It behaves just like a standard my_dict[key], returning the value for the key (which may be the newly set value).</p>
9
2010-02-04T10:32:38Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
7,722,107
<p>I was looking for it, didn't found it on web then tried my luck with Try/Error and found it</p> <pre><code>my_dict = {} if my_dict.__contains__(some_key): my_dict[some_key] += 1 else: my_dict[some_key] = 1 </code></pre>
1
2011-10-11T06:23:38Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
7,924,128
<p>I personally like using <code>setdefault()</code></p> <pre><code>my_dict = {} my_dict.setdefault(some_key, 0) my_dict[some_key] += 1 </code></pre>
14
2011-10-28T01:03:34Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
13,802,641
<p>Here's one-liner that I came up with recently for solving this problem. It's based on the <a href="http://docs.python.org/2/library/stdtypes.html#dict.setdefault" rel="nofollow">setdefault</a> dictionary method:</p> <pre><code>my_dict = {} my_dict[key] = my_dict.setdefault(key, 0) + 1 </code></pre>
2
2012-12-10T14:12:56Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.</p>
163
2009-01-23T14:35:39Z
34,528,177
<p>A bit late but this should work.</p> <pre><code>my_dict = {} my_dict[key] = my_dict[key] + 1 if key in my_dict else 1 </code></pre>
1
2015-12-30T11:00:52Z
[ "python", "dictionary" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it is, does this have any relevance when it goes to the printer? </p>
4
2009-01-23T16:16:33Z
473,514
<p>Printers have various resolutions in which they print. If you select a print resolution of 200 DPI for instance (or if it's set as default in the printer driver), then a 200 pixel image should be one inch in size.</p>
1
2009-01-23T16:20:13Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it is, does this have any relevance when it goes to the printer? </p>
4
2009-01-23T16:16:33Z
473,524
<p>As of PIL 1.1.5, there is a way to get the DPI:</p> <pre><code>im = ... # get image into PIL image instance dpi = im.info["dpi"] # retrive the DPI print dpi # (x-res, y-res) im.info["dpi"] = new dpi # (x-res, y-res) im.save("PNG") # uses the new DPI </code></pre>
6
2009-01-23T16:22:41Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it is, does this have any relevance when it goes to the printer? </p>
4
2009-01-23T16:16:33Z
473,539
<p>Much is going to depend on the software you're using to print. If you're placing the image in a Word document, it will scale according to the DPI, up to the width of your page. If you're putting it on a web page, the DPI will not matter at all.</p>
0
2009-01-23T16:27:19Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it is, does this have any relevance when it goes to the printer? </p>
4
2009-01-23T16:16:33Z
473,556
<p>Both image print size and resolution are relevant to printing an image of a specific scale and quality. Bear in mind that if the image is then included with a desktop publishing workspace (Word, InDesign) or even a web page, the image is then subject to any specified resolution in the parent document -- this won't necessarily alter the relative scale of the image in the case of desktop publishing programs but will alter image quality.</p> <p>And yes, all images have a resolution property, which answers half your question - I don't know Python...</p>
1
2009-01-23T16:32:21Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it is, does this have any relevance when it goes to the printer? </p>
4
2009-01-23T16:16:33Z
21,163,772
<p>I found a very simple way to get dpi information into the png:</p> <p>im.save('myfile.png',dpi=[600,600])</p> <p>Unfortunately I did not find this documented anywhere and had to dig into the PIL source code.</p>
2
2014-01-16T13:56:56Z
[ "python", "python-imaging-library", "dpi" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
473,702
<p>Sander Marechal's <a href="http://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">code sample</a> is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had to do it over.</p>
114
2009-01-23T17:06:11Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
474,802
<p>80% of the time, when folks say "daemon", they only want a server. Since the question is perfectly unclear on this point, it's hard to say what the possible domain of answers could be. Since a server is adequate, start there. If an actual "daemon" is actually needed (this is rare), read up on <code>nohup</code> as a way to daemonize a server.</p> <p>Until such time as an actual daemon is actually required, just write a simple server.</p> <p>Also look at the <a href="http://www.python.org/doc/2.5.2/lib/module-wsgiref.html" rel="nofollow">WSGI reference</a> implementation.</p> <p>Also look at the <a href="http://www.python.org/doc/2.5.2/lib/module-SimpleHTTPServer.html" rel="nofollow">Simple HTTP Server</a>.</p> <p>"Are there any additional things that need to be considered? " Yes. About a million things. What protocol? How many requests? How long to service each request? How frequently will they arrive? Will you use a dedicated process? Threads? Subprocesses? Writing a daemon is a big job. </p>
-23
2009-01-23T22:06:27Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
475,575
<p>The easiest way to create daemon with Python is to use the <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> event-driven framework. It handles all of the stuff necessary for daemonization for you. It uses the <a href="http://en.wikipedia.org/wiki/Reactor_pattern" rel="nofollow">Reactor Pattern</a> to handle concurrent requests.</p>
-3
2009-01-24T05:37:07Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
688,448
<p>There are <strong>many fiddly things</strong> to take care of when becoming a <a href="http://www.python.org/dev/peps/pep-3143/#correct-daemon-behaviour">well-behaved daemon process</a>:</p> <ul> <li><p>prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)</p></li> <li><p>behave correctly inside a <code>chroot</code> gaol</p></li> <li><p>set UID, GID, working directory, umask, and other process parameters appropriately for the use case</p></li> <li><p>relinquish elevated <code>suid</code>, <code>sgid</code> privileges</p></li> <li><p>close all open file descriptors, with exclusions depending on the use case</p></li> <li><p>behave correctly if started inside an already-detached context, such as <code>init</code>, <code>inetd</code>, etc.</p></li> <li><p>set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case</p></li> <li><p>redirect the standard streams <code>stdin</code>, <code>stdout</code>, <code>stderr</code> since a daemon process no longer has a controlling terminal</p></li> <li><p>handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave</p></li> <li><p>allow proper cleanup when the process is terminated</p></li> <li><p>actually become a daemon process without leading to zombies</p></li> </ul> <p>Some of these are <strong>standard</strong>, as described in canonical Unix literature (<em>Advanced Programming in the UNIX Environment</em>, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and <a href="http://stackoverflow.com/questions/688343/reference-for-proper-handling-of-pid-file-on-unix">PID file handling</a>, are <strong>conventional behaviour</strong> most daemon users would expect but that are less standardised.</p> <p>All of these are covered by the <strong><a href="http://www.python.org/dev/peps/pep-3143">PEP 3143</a> “Standard daemon process library” specification</strong>. The <a href="http://pypi.python.org/pypi/python-daemon/">python-daemon</a> reference implementation works on Python 2.7 or later, and Python 3.2 or later.</p>
133
2009-03-27T03:38:06Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
5,412,949
<p>Note the <a href="http://pypi.python.org/pypi/python-daemon/">python-daemon</a> package which solves a lot of problems behind daemons out of the box.</p> <p>Among other features it enables to (from Debian package description):</p> <ul> <li>Detach the process into its own process group.</li> <li>Set process environment appropriate for running inside a chroot.</li> <li>Renounce suid and sgid privileges.</li> <li>Close all open file descriptors.</li> <li>Change the working directory, uid, gid, and umask.</li> <li>Set appropriate signal handlers.</li> <li>Open new file descriptors for stdin, stdout, and stderr.</li> <li>Manage a specified PID lock file.</li> <li>Register cleanup functions for at-exit processing.</li> </ul>
38
2011-03-23T23:28:03Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
8,396,039
<p>Here is a relatively new python module that popped up in Hacker News. Looks pretty useful, can be used to convert a python script into daemon mode from inside the script. <a href="https://github.com/kasun/YapDi">link</a></p>
6
2011-12-06T06:11:26Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
9,047,339
<p>Here's my basic 'Howdy World' Python daemon that I start with, when I'm developing a new daemon application.</p> <pre><code>#!/usr/bin/python import time from daemon import runner class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/foo.pid' self.pidfile_timeout = 5 def run(self): while True: print("Howdy! Gig'em! Whoop!") time.sleep(10) app = App() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() </code></pre> <p>Note that you'll need the <code>python-deaemon</code> library. In Ubuntu, you would:</p> <pre><code>sudo apt-get install python-daemon </code></pre> <p>Then just start it with <code>./howdy.py start</code>, and stop it with <code>./howdy.py stop</code>.</p>
74
2012-01-28T17:33:44Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
17,255,175
<p>An alternative -- create a normal, non-daemonized Python program then externally daemonize it using <a href="http://supervisord.org/" rel="nofollow" title="supervisord">supervisord</a>. This can save a lot of headaches, and is *nix- and language-portable.</p>
17
2013-06-22T20:50:01Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
21,913,617
<p>One more to thing to think about when daemonizing in python:</p> <p>If your are using python <strong>logging</strong> and you want to continue using it after daemonizing, make sure to call <code>close()</code> on the handlers (particularly the file handlers).</p> <p>If you don't do this the handler can still think it has files open, and your messages will simply disappear - in other words make sure the logger knows its files are closed!</p> <p>This assumes when you daemonise you are closing ALL the open file descriptors indiscriminatingly - instead you could try closing all but the log files (but it's usually simpler to close all then reopen the ones you want).</p>
2
2014-02-20T16:21:09Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
25,852,855
<p>since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: <a href="https://pypi.python.org/pypi/pep3143daemon" rel="nofollow">pep3143daemon</a></p> <p>pep3143daemon should support at least python 2.6, 2.7 and 3.x</p> <p>It also contains a PidFile class.</p> <p>The library only depends on the standard library and on the six module.</p> <p>It can be used as a drop in replacement for python-daemon.</p> <p>Here is the <a href="http://pep3143daemon.readthedocs.org/en/latest/" rel="nofollow">documentation</a>.</p>
4
2014-09-15T16:43:37Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
30,314,206
<p>Probably not a direct answer to the question, but systemd can be used to run your application as a daemon. Here is an example:</p> <pre><code>[Unit] Description=Python daemon After=syslog.target After=network.target [Service] Type=simple User=&lt;run as user&gt; Group=&lt;run as group group&gt; ExecStart=/usr/bin/python &lt;python script home&gt;/script.py # Give the script some time to startup TimeoutSec=300 [Install] WantedBy=multi-user.target </code></pre> <p>I prefer this method because a lot of the work is done for you, and then your daemon script behaves similarly to the rest of your system.</p> <p>-Orby</p>
3
2015-05-18T23:11:12Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
39,442,716
<p>I am afraid the daemon module mentioned by @Dustin didn't work for me. Instead I installed <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">python-daemon</a> and used the following code:</p> <pre><code># filename myDaemon.py import sys import daemon sys.path.append('/home/ubuntu/samplemodule') # till __init__.py from samplemodule import moduleclass with daemon.DaemonContext(): moduleclass.do_running() # I have do_running() function and whatever I was doing in __main__() in module.py I copied in it. </code></pre> <p>Running is easy</p> <pre><code>&gt; python myDaemon.py </code></pre> <p>just for completeness here is samplemodule directory content</p> <pre><code>&gt;ls samplemodule __init__.py __init__.pyc moduleclass.py </code></pre> <p>The content of moduleclass.py can be</p> <pre><code>class moduleclass(): ... def do_running(): m = moduleclass() # do whatever daemon is required to do. </code></pre>
1
2016-09-12T02:43:11Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
185
2009-01-23T16:48:06Z
39,486,303
<p>This function will transform an application to a daemon:</p> <pre><code>import sys import os def daemonize(): try: pid = os.fork() if pid &gt; 0: # exit first parent sys.exit(0) except OSError as err: sys.stderr.write('_Fork #1 failed: {0}\n'.format(err)) sys.exit(1) # decouple from parent environment os.chdir('/') os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid &gt; 0: # exit from second parent sys.exit(0) except OSError as err: sys.stderr.write('_Fork #2 failed: {0}\n'.format(err)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'w') se = open(os.devnull, 'w') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) </code></pre>
1
2016-09-14T08:54:22Z
[ "python", "daemon" ]
file upload status information
473,937
<p>Im making a small python script to upload files on the net. The script is working correctly, and now I want to add a simple progress bar that indicates the amount of uploading left. my question is -how do I get the upload status information from the server where im uploading the file, assuming it is possible...I am using curl and pycurl to make the http requests in python. Any help will be much appreciated, Thanks!!</p>
2
2009-01-23T18:21:26Z
474,041
<p>Check out the documentation here: <a href="http://pycurl.sourceforge.net/doc/callbacks.html" rel="nofollow">http://pycurl.sourceforge.net/doc/callbacks.html</a> for callbacks. Best of luck!</p>
2
2009-01-23T18:56:20Z
[ "python", "upload", "curl" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are there, but I can list all of them globbing the directory via something like "bot_*.py"</p> <p>I think this is something about "meta programming", but how could be the best (most elegant) way to do it?</p>
3
2009-01-23T18:30:25Z
474,004
<p>You could use <a href="http://docs.python.org/library/functions.html#__import__" rel="nofollow"><code>__import__()</code></a> to load each module, use <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> to find all objects in each module, find all objects which are classes, instantiate them, and run the <code>go()</code> method:</p> <pre><code>import types for module_name in list_of_modules_to_load: module = __import__(module_name) for name in dir(module): object = module.__dict__[name] if type(object) == types.ClassType: object().go() </code></pre>
4
2009-01-23T18:43:50Z
[ "python", "metaprogramming" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are there, but I can list all of them globbing the directory via something like "bot_*.py"</p> <p>I think this is something about "meta programming", but how could be the best (most elegant) way to do it?</p>
3
2009-01-23T18:30:25Z
474,019
<p>Here is one way to do this off the top of my head where I have to presume the structure of your modules a bit:</p> <pre>mainDir/ runner.py package/ __init__.py bot_moduleA.py bot_moduleB.py bot_moduleC.py</pre> <p>In runner you could find this:</p> <pre><code> import types import package for moduleName in dir(package): module = package.__dict__[moduleName] if type(module) != types.ModuleType: continue for klassName in dir(module): klass = module.__dict__[klassName] if type(klass) != types.ClassType: continue klass().go() </code></pre>
1
2009-01-23T18:49:37Z
[ "python", "metaprogramming" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are there, but I can list all of them globbing the directory via something like "bot_*.py"</p> <p>I think this is something about "meta programming", but how could be the best (most elegant) way to do it?</p>
3
2009-01-23T18:30:25Z
474,185
<p>I would try:</p> <pre><code>import glob import os filelist = glob.glob('bot_*.py') for f in filelist: context = {} exec(open(f).read(), context) klassname = os.path.basename(f)[:-3] klass = context[klassname] klass().go() </code></pre> <p>This will only run classes similarly named to the module, which I think is what you want. It also doesn't have the requirement of the top level directory to be a package.</p> <p>Beware that glob returns the complete path, including preceding directories, hence the use os.path.basename(f)[:-3] to get the class name.</p>
1
2009-01-23T19:35:36Z
[ "python", "metaprogramming" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are there, but I can list all of them globbing the directory via something like "bot_*.py"</p> <p>I think this is something about "meta programming", but how could be the best (most elegant) way to do it?</p>
3
2009-01-23T18:30:25Z
474,278
<pre><code>def run_all(path): import glob, os print "Exploring %s" % path for filename in glob.glob(path + "/*.py"): # modulename = "bot_paperino" modulename = os.path.splitext(os.path.split(filename)[-1])[0] # classname = "Paperino" classname = modulename.split("bot_")[-1].capitalize() # package = "path.bot_paperino" package = filename.replace("\\", "/").replace("/", ".")[:-3] mod = __import__(package) if classname in mod.__dict__[modulename].__dict__.keys(): obj = mod.__dict__[modulename].__dict__[classname]() if hasattr(obj, "go"): obj.go() if __name__ == "__main__": import sys # Run on each directory passed on command line for path in sys.argv[1:]: run_all(sys.argv[1]) </code></pre> <p>You need a <code>__init__.py</code> in each path you want to "run". Change "bot_" at your will. Run on windows and linux.</p>
3
2009-01-23T20:00:25Z
[ "python", "metaprogramming" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
473,983
<pre><code>import random random.shuffle(array) </code></pre>
242
2009-01-23T18:37:27Z
[ "python", "arrays", "random", "order" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
473,988
<pre><code>import random random.shuffle(array) </code></pre>
75
2009-01-23T18:38:14Z
[ "python", "arrays", "random", "order" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
8,582,589
<p>The other answers are the easiest, however it's a bit annoying that the <code>random.shuffle</code> method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:</p> <pre><code> import random def my_shuffle(array): random.shuffle(array) return array </code></pre> <p>Then you can do lines like:</p> <pre><code> for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']): </code></pre>
16
2011-12-20T22:05:30Z
[ "python", "arrays", "random", "order" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
19,631,040
<p>When dealing with regular Python lists, <code>random.shuffle()</code> will do the job just as the previous answers show.</p> <p>But when it come to <code>ndarray</code>(<code>numpy.array</code>), <code>random.shuffle</code> seems to break the original <code>ndarray</code>. Here is an example:</p> <pre><code>import random import numpy as np import numpy.random a = np.array([1,2,3,4,5,6]) a.shape = (3,2) print a random.shuffle(a) # a will definitely be destroyed print a </code></pre> <p>Just use: <code>np.random.shuffle(a)</code></p> <p>Like <code>random.shuffle</code>, <code>np.random.shuffle</code> shuffles the array in-place.</p>
7
2013-10-28T09:23:27Z
[ "python", "arrays", "random", "order" ]
Which GTK widget combination to use for scrollable column of widgets?
474,034
<p>I'm working with PyGTK, trying to come up with a combination of widgets that will do the following:</p> <ul> <li>Let me add an endless number of widgets in a column</li> <li>Provide a vertical scrollbar to get to the ones that run off the bottom</li> <li>Make the widgets' width adjust to fill available horizontal space when the window is resized</li> </ul> <p>Thanks - I'm new to GTK.</p>
3
2009-01-23T18:53:35Z
474,134
<ul> <li>An endless number of widgets in a column: Sounds like a GtkVBox.</li> <li>Vertical scrollbar: Put your VBox in a GtkScrolledWindow.</li> <li>Horizontal stretching: This requires setting the appropriate properties for the VBox, ScrolledWindow, and your other widgets. At least in Glade the defaults seem to mostly handle this (You will probably want to change the scrollbar policy of the ScrolledWindow).</li> </ul> <p>Now for the trick. If you just do what I've listed above, the contents of the VBox will try to resize vertically as well as horizontally, and you won't get your scrollbar. The solution is to place your VBox in a GtkViewport.</p> <p>So the final hierarchy is ScrolledWindow( Viewport( VBox( widgets ) ) ).</p>
7
2009-01-23T19:23:01Z
[ "python", "gtk", "pygtk", "widget" ]
Which GTK widget combination to use for scrollable column of widgets?
474,034
<p>I'm working with PyGTK, trying to come up with a combination of widgets that will do the following:</p> <ul> <li>Let me add an endless number of widgets in a column</li> <li>Provide a vertical scrollbar to get to the ones that run off the bottom</li> <li>Make the widgets' width adjust to fill available horizontal space when the window is resized</li> </ul> <p>Thanks - I'm new to GTK.</p>
3
2009-01-23T18:53:35Z
5,440,831
<p>What Steve said in code:</p> <pre><code>vbox = gtk.VBox() vbox.pack_start(widget1, 1, 1) ## fill and expand vbox.pack_start(widget2, 1, 1) ## fill and expand vbox.pack_start(widget3, 1, 1) ## fill and expand swin = gtk.ScrolledWindow() swin.add_with_viewport(vbox) </code></pre>
0
2011-03-26T06:54:52Z
[ "python", "gtk", "pygtk", "widget" ]
how to pass id from url to post_save_redirect in urls.py
474,203
<p><br /> I have several objects in the database. Url to edit an object using the generic view looks like <code>site.com/cases/edit/123/</code> where <code>123</code> is an id of the particular object. Consider the <code>cases/url.py</code> contents:</p> <pre><code>url(r'edit/(?P&lt;object_id&gt;\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'), </code></pre> <p>where <code>update_object</code> is a generic view. How to construct the <code>post_save_redirect</code> to point to <code>site.com/cases/edit/123/</code>. My problem is, that I don't know how to pass the <code>id</code> of the object to redirect function. I tried something like:</p> <pre><code>'post_save_redirect': 'edit/(?P&lt;object_id&gt;\d{1,5})/' 'post_save_redirect': 'edit/' + str(object_id) + '/' </code></pre> <p>but obviously none of these work. <code>reverse</code> function was suggested, but how to pass the particular <code>id</code>?</p> <pre><code>'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???}) </code></pre> <p><code>{% url %}</code> in the temple also requires passing the <code>id</code> of the particular object. The <code>id</code> can be passed via <code>extra_context</code>:</p> <pre><code>extra_context = {'object_id': ???} </code></pre> <p>In all the cases the problem is to get <code>object_id</code> from the url. <br /><br /></p> <p>regards<br /> chriss</p>
0
2009-01-23T19:42:18Z
474,524
<p>First, read up on the <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse" rel="nofollow">reverse</a> function.</p> <p>Second, read up on the <code>{%</code> <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow">url</a> <code>%}</code> tag.</p> <p>You use the <code>reverse</code> function in a view to generate the expected redirect location.</p> <p>Also, you should be using the <code>{% url %}</code> tag in your templates.</p>
0
2009-01-23T21:05:47Z
[ "python", "django", "django-urls" ]
how to pass id from url to post_save_redirect in urls.py
474,203
<p><br /> I have several objects in the database. Url to edit an object using the generic view looks like <code>site.com/cases/edit/123/</code> where <code>123</code> is an id of the particular object. Consider the <code>cases/url.py</code> contents:</p> <pre><code>url(r'edit/(?P&lt;object_id&gt;\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'), </code></pre> <p>where <code>update_object</code> is a generic view. How to construct the <code>post_save_redirect</code> to point to <code>site.com/cases/edit/123/</code>. My problem is, that I don't know how to pass the <code>id</code> of the object to redirect function. I tried something like:</p> <pre><code>'post_save_redirect': 'edit/(?P&lt;object_id&gt;\d{1,5})/' 'post_save_redirect': 'edit/' + str(object_id) + '/' </code></pre> <p>but obviously none of these work. <code>reverse</code> function was suggested, but how to pass the particular <code>id</code>?</p> <pre><code>'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???}) </code></pre> <p><code>{% url %}</code> in the temple also requires passing the <code>id</code> of the particular object. The <code>id</code> can be passed via <code>extra_context</code>:</p> <pre><code>extra_context = {'object_id': ???} </code></pre> <p>In all the cases the problem is to get <code>object_id</code> from the url. <br /><br /></p> <p>regards<br /> chriss</p>
0
2009-01-23T19:42:18Z
476,720
<p>In short what you need to do is wrap the update_object function.</p> <pre><code>def update_object_wrapper(request, object_id, *args, **kwargs): redirect_to = reverse('your object edit url name', object_id) return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs) </code></pre>
1
2009-01-24T21:52:17Z
[ "python", "django", "django-urls" ]
how to pass id from url to post_save_redirect in urls.py
474,203
<p><br /> I have several objects in the database. Url to edit an object using the generic view looks like <code>site.com/cases/edit/123/</code> where <code>123</code> is an id of the particular object. Consider the <code>cases/url.py</code> contents:</p> <pre><code>url(r'edit/(?P&lt;object_id&gt;\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'), </code></pre> <p>where <code>update_object</code> is a generic view. How to construct the <code>post_save_redirect</code> to point to <code>site.com/cases/edit/123/</code>. My problem is, that I don't know how to pass the <code>id</code> of the object to redirect function. I tried something like:</p> <pre><code>'post_save_redirect': 'edit/(?P&lt;object_id&gt;\d{1,5})/' 'post_save_redirect': 'edit/' + str(object_id) + '/' </code></pre> <p>but obviously none of these work. <code>reverse</code> function was suggested, but how to pass the particular <code>id</code>?</p> <pre><code>'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???}) </code></pre> <p><code>{% url %}</code> in the temple also requires passing the <code>id</code> of the particular object. The <code>id</code> can be passed via <code>extra_context</code>:</p> <pre><code>extra_context = {'object_id': ???} </code></pre> <p>In all the cases the problem is to get <code>object_id</code> from the url. <br /><br /></p> <p>regards<br /> chriss</p>
0
2009-01-23T19:42:18Z
6,836,357
<p>Right from the docs at: <a href="https://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-create-update-create-object" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-create-update-create-object</a></p> <p>post_save_redirect may contain dictionary string formatting, which will be interpolated against the object's field attributes. For example, you could use post_save_redirect="/polls/%(slug)s/".</p>
0
2011-07-26T20:42:27Z
[ "python", "django", "django-urls" ]
Python pysqlite not accepting my qmark parameterization
474,261
<p>I think I am being a bonehead, maybe not importing the right package, but when I do...</p> <pre><code> from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "insert into asgn values ('?', ?)" self.cursor.execute(stmt, (sys.argv[2],)) self.cursor.execute(stmt2, [sys.argv[2], sys.argv[3]]) ... </code> I get the error pysqlite2.dbapi2.OperationalError: near "?": syntax error </pre> <p>This makes very little sense to me, as the docs show that pysqlite is qmark parametrized. I am new to python and db-api though, help me out! THANKS</p>
1
2009-01-23T19:55:18Z
474,296
<p>That's because parameters can only be passed to VALUES. The table name can't be parametrized.</p> <p>Also you have quotes around a parametrized argument on the second query. Remove the quotes, escaping is handled by the underlining library automatically for you.</p>
7
2009-01-23T20:05:50Z
[ "python", "sqlite", "pysqlite", "python-db-api" ]
Python pysqlite not accepting my qmark parameterization
474,261
<p>I think I am being a bonehead, maybe not importing the right package, but when I do...</p> <pre><code> from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "insert into asgn values ('?', ?)" self.cursor.execute(stmt, (sys.argv[2],)) self.cursor.execute(stmt2, [sys.argv[2], sys.argv[3]]) ... </code> I get the error pysqlite2.dbapi2.OperationalError: near "?": syntax error </pre> <p>This makes very little sense to me, as the docs show that pysqlite is qmark parametrized. I am new to python and db-api though, help me out! THANKS</p>
1
2009-01-23T19:55:18Z
474,318
<p>Try removing the quotes in the line that assigns to <code>stmt2</code>:</p> <pre><code> stmt2 = "insert into asgn values (?, ?)" </code></pre> <p>Also, as nosklo says, you can't use question-mark parameterisation with CREATE TABLE statements. Stick the table name into the SQL directly.</p>
2
2009-01-23T20:10:00Z
[ "python", "sqlite", "pysqlite", "python-db-api" ]
Python pysqlite not accepting my qmark parameterization
474,261
<p>I think I am being a bonehead, maybe not importing the right package, but when I do...</p> <pre><code> from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "insert into asgn values ('?', ?)" self.cursor.execute(stmt, (sys.argv[2],)) self.cursor.execute(stmt2, [sys.argv[2], sys.argv[3]]) ... </code> I get the error pysqlite2.dbapi2.OperationalError: near "?": syntax error </pre> <p>This makes very little sense to me, as the docs show that pysqlite is qmark parametrized. I am new to python and db-api though, help me out! THANKS</p>
1
2009-01-23T19:55:18Z
571,431
<p>If you really want to do it, try something like this:</p> <p>def read(db="projects"):</p> <pre><code>sql = "select * from %s" sql = sql % db c.execute(sql) </code></pre>
1
2009-02-20T22:09:07Z
[ "python", "sqlite", "pysqlite", "python-db-api" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.</p> <p>To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.</p> <p>The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.</p> <p>Aside from the implementation difficulty and the problem I described above, what problems are there with this idea?</p>
3
2009-01-23T19:59:01Z
474,540
<p>Another thing I've considered is making this the default behavior across the board, but allow languages (meaning a set of macros to parse a given language) to throw a parse error at compile-time. Python 2.5 in my system, for example, would do this.</p> <p>Instead of the stub idea, simply recompile functions that couldn't be handled completely at compile-time when they're executed. This will also make self-modifying code easier, as you can modify the code and recompile it at runtime.</p>
1
2009-01-23T21:09:05Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.</p> <p>To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.</p> <p>The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.</p> <p>Aside from the implementation difficulty and the problem I described above, what problems are there with this idea?</p>
3
2009-01-23T19:59:01Z
483,299
<p>Here are a few possible problems:</p> <ul> <li>You may find it difficult to provide the user with helpful error messages in case of a problem. This seems likely, as any compilation-time syntax error could be just a syntax extension.</li> <li>Performance hit.</li> </ul> <p>I was trying to find some discussion of the pluses, minuses, and/or implementation of dynamic parsing in Perl 6, but I couldn't find anything appropriate. However, you may find this quote from Nicklaus Wirth (designer of Pascal and other languages) interesting:</p> <blockquote> <p>The phantasies of computer scientists in the 1960s knew no bounds. Spurned by the success of automatic syntax analysis and parser generation, some proposed the idea of the flexible, or at least extensible language. The notion was that a program would be preceded by syntactic rules which would then guide the general parser while parsing the subsequent program. A step further: The syntax rules would not only precede the program, but they could be interspersed anywhere throughout the text. For example, if someone wished to use a particularly fancy private form of for statement, he could do so elegantly, even specifying different variants for the same concept in different sections of the same program. The concept that languages serve to communicate between humans had been completely blended out, as apparently everyone could now define his own language on the fly. The high hopes, however, were soon damped by the difficulties encountered when trying to specify, what these private constructions should mean. As a consequence, the intreaguing idea of extensible languages faded away rather quickly.</p> </blockquote> <p><em>Edit</em>: Here's Perl 6's <a href="http://svn.pugscode.org/pugs/docs/Perl6/Spec/S06-routines.pod" rel="nofollow">Synopsis 6: Subroutines</a>, unfortunately in markup form because I couldn't find an updated, formatted version; search within for "macro". Unfortunately, it's not <em>too</em> interesting, but you may find some things relevant, like Perl 6's one-pass parsing rule, or its syntax for abstract syntax trees. The approach Perl 6 takes is that a macro is a function that executes immediately after its arguments are parsed and returns either an AST or a string; Perl 6 continues parsing as if the source actually contained the return value. There is mention of generation of error messages, but they make it seem like if macros return ASTs, you can do alright.</p>
3
2009-01-27T12:58:26Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.</p> <p>To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.</p> <p>The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.</p> <p>Aside from the implementation difficulty and the problem I described above, what problems are there with this idea?</p>
3
2009-01-23T19:59:01Z
483,465
<p>You'll probably need to delimit the bits of input text with unknown syntax, so that the rest of the syntax tree can be resolved, apart from some character sequences nodes which will be expanded later. Depending on your top level syntax, that may be fine. </p> <p>You may find that the parsing algorithm and the lexer and the interface between them all need updating, which might rule out most compiler creation tools.</p> <p>(The more usual approach is to use string constants for this purpose, which can be parsed to a little interpreter at run time).</p>
0
2009-01-27T13:52:40Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.</p> <p>To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.</p> <p>The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.</p> <p>Aside from the implementation difficulty and the problem I described above, what problems are there with this idea?</p>
3
2009-01-23T19:59:01Z
485,315
<p>Pushing this one step further, you could do "lazy" parsing and always only parse enough to evaluate the next statement. Like some kind of just-in-time parser. Then syntax errors could become normal runtime errors that just raise a normal Exception that could be handled by surrounding code:</p> <pre><code>def fun(): not implemented yet try: fun() except: pass </code></pre> <p>That would be an interesting effect, but if it's useful or desirable is a different question. Generally it's good to know about errors even if you don't call the code at the moment.</p> <p>Macros would not be evaluated until control reaches them and naturally the parser would already know all previous definitions. Also the macro definition could maybe even use variables and data that the program has calculated so far (like adding some syntax for all elements in a previously calculated list). But this is probably a bad idea to start writing self-modifying programs for things that could usually be done as well directly in the language. This could get confusing...</p> <p>In any case you should make sure to parse code only once, and if it is executed a second time use the already parsed expression, so that it doesn't lead to performance problems.</p>
2
2009-01-27T21:22:02Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.</p> <p>To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.</p> <p>The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.</p> <p>Aside from the implementation difficulty and the problem I described above, what problems are there with this idea?</p>
3
2009-01-23T19:59:01Z
493,889
<p>I don't think your approach would work very well. Let's take a simple example written in pseudo-code:</p> <pre><code>define some syntax M1 with definition D1 if _whatever_: define M1 to do D2 else: define M1 to do D3 code that uses M1 </code></pre> <p>So there is one example where, if you allow syntax redefinition at runtime, you have a problem (since by your approach the code that uses M1 would be compiled by definition D1). Note that verifying if syntax redefinition occurs is undecidable. An over-approximation could be computed by some kind of typing system or some other kind of static analysis, but Python is not well known for this :D.</p> <p>Another thing that bothers me is that your solution does not 'feel' right. I find it evil to store source code you can't parse just because you may be able to parse it at runtime.</p> <p>Another example that jumps to mind is this:</p> <pre><code>...function definition fun1 that calls fun2... define M1 (at runtime) use M1 ...function definition for fun2 </code></pre> <p>Technically, when you use M1, you cannot parse it, so you need to keep the rest of the program (including the function definition of fun2) in source code. When you run the entire program, you'll see a call to fun2 that you cannot call, even if it's defined.</p>
0
2009-01-29T23:04:41Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.</p> <p>To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.</p> <p>The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.</p> <p>Aside from the implementation difficulty and the problem I described above, what problems are there with this idea?</p>
3
2009-01-23T19:59:01Z
500,373
<p>Here are some ideas from my master's thesis, which may or may not be helpful. The thesis was about robust parsing of natural language. The main idea: given a context-free grammar for a language, try to parse a given text (or, in your case, a python program). If parsing failed, you will have a partially generated parse tree. Use the tree structure to suggest new grammar rules that will better cover the parsed text. I could send you my thesis, but unless you read Hebrew this will probably not be useful.</p> <p>In a nutshell: I used a <a href="http://en.wikipedia.org/wiki/Bottom-up_parser" rel="nofollow">bottom-up</a> <a href="http://en.wikipedia.org/wiki/Chart_parser" rel="nofollow">chart parser</a>. This type of parser generates edges for productions from the grammar. Each edge is marked with the part of the tree that was consumed. Each edge gets a score according to how close it was to full coverage, for example: </p> <pre><code>S -&gt; NP . VP </code></pre> <p>Has a score of one half (We succeeded in covering the NP but not the VP). The highest-scored edges suggest a new rule (such as X->NP). In general, a chart parser is less efficient than a common LALR or LL parser (the types usually used for programming languages) - O(n^3) instead of O(n) complexity, but then again you are trying something more complicated than just parsing an existing language. If you can do something with the idea, I can send you further details. I believe looking at natural language parsers may give you some other ideas.</p>
1
2009-02-01T07:17:26Z
[ "python", "parsing", "macros", "language-design" ]
Getting attributes of a Python package that I don't have the name of, until runtime
474,331
<p>In a Python package, I have a string containing (presumably) the name of a subpackage. From that subpackage, I want to retrieve a tuple of constants...I'm really not even sure how to proceed in doing this, though.</p> <pre><code>#!/usr/bin/python "" The Alpha Package Implements functionality of a base package under the 'alpha' namespace "" def get_params(packagename): # Here, I want to get alpha.&lt;packagename&gt;.REQUIRED_PARAMS pass </code></pre> <p>So, later in my code I might have:</p> <pre><code>#!/usr/bin/python import alpha alpha.get_params('bravo') # should return alpha.bravo.REQUIRED_PARAMS alpha.get_params('charlie') # should return alpha.charlie.REQUIRED_PARAMS </code></pre>
2
2009-01-23T20:13:10Z
474,352
<p>If I correctly understand what you want, I think something roughly like this should work:</p> <pre><code>def get_params(packagename): module = __import__('alpha.%s' % packagename) return module.__dict__['REQUIRED_PARAMS'] </code></pre>
5
2009-01-23T20:17:26Z
[ "python", "package" ]
Python: Use the codecs module or use string function decode?
474,373
<p>I have a text file that is encoded in UTF-8. I'm reading it in to analyze and plot some data. I would like the file to be read in as ascii. Would it be best to use the codecs module or use the builtin string decode method? Also, the file is divided up as a csv, so could the csv module also be a valid solution?</p> <p>Thanks for your help.</p>
0
2009-01-23T20:23:38Z
474,411
<p>Do you mean that your file is encoded in UTF-8? ("Unicode" is not an encoding... Required reading: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">http://www.joelonsoftware.com/articles/Unicode.html</a>) I'm not 100% sure but I think you should be able to read a UTF-8 encoded file with the csv module, and you can convert the strings which contain special characters to Python's unicode strings (<em>edit:</em> if you need to) after reading.</p> <p>There are a few examples of using csv with UTF-8 encoded data at <a href="http://docs.python.org./library/csv.html#csv-examples" rel="nofollow">http://docs.python.org./library/csv.html#csv-examples</a>; it might help you to look at them.</p>
5
2009-01-23T20:36:12Z
[ "python", "unicode", "csv", "decode", "codec" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
474,543
<p>Use the <a href="http://docs.python.org/library/sched.html" rel="nofollow">sched</a> module, which implements a general purpose event scheduler.</p> <pre><code>import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print "Doing stuff..." # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run() </code></pre>
78
2009-01-23T21:09:33Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
474,559
<p>The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.</p>
3
2009-01-23T21:12:17Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
474,570
<p>You might want to consider <a href="http://twistedmatrix.com/trac/">Twisted</a> which is a python networking library that implements the <a href="http://en.wikipedia.org/wiki/Reactor_pattern">Reactor Pattern</a>.</p> <pre><code>from twisted.internet import task from twisted.internet import reactor timeout = 60.0 # Sixty seconds def doWork(): #do work here pass l = task.LoopingCall(doWork) l.start(timeout) # call every sixty seconds reactor.run() </code></pre> <p>While "while True: sleep(60)" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution</p>
30
2009-01-23T21:14:06Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
13,217,744
<p>The easier way I believe to be:</p> <pre><code>import time def executeSomething(): #code here time.sleep(60) while True: executeSomething() </code></pre> <p>This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D</p>
21
2012-11-04T10:26:10Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
24,088,342
<p>I faced a similar problem some time back. May be <a href="http://cronus.readthedocs.org" rel="nofollow">http://cronus.readthedocs.org</a> might help?</p> <p>For v0.2, the following snippet works</p> <pre><code>import cronus.beat as beat beat.set_rate(2) # 2 Hz while beat.true(): # do some time consuming work here beat.sleep() # total loop duration would be 0.5 sec </code></pre>
4
2014-06-06T18:21:58Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
25,251,804
<p>Just lock your time loop to the system clock. Easy.</p> <pre><code>import time starttime=time.time() while True: print "tick" time.sleep(60.0 - ((time.time() - starttime) % 60.0)) </code></pre>
31
2014-08-11T20:25:25Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.</p> <p>In <a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python">this question about a cron implemented in Python</a>, the solution appears to effectively just <a href="http://docs.python.org/library/time.html#time.sleep">sleep()</a> for x seconds. I don't need such advanced functionality so perhaps something like this would work</p> <pre><code>while True: # Code executed here time.sleep(60) </code></pre> <p>Are there any foreseeable problems with this code?</p>
68
2009-01-23T21:07:05Z
38,317,060
<p>If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/Network intensive tasks.</p> <p>Here's the code I've posted in a similar question, with start() and stop() control:</p> <pre><code>from threading import Timer class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False </code></pre> <p>Usage:</p> <pre><code>from time import sleep def hello(name): print "Hello %s!" % name print "starting..." rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start() try: sleep(5) # your long-running job goes here... finally: rt.stop() # better in a try/finally block to make sure the program ends! </code></pre> <p>Features:</p> <ul> <li>Standard library only, no external dependencies</li> <li><code>start()</code> and <code>stop()</code> are safe to call multiple times even if the timer has already started/stopped</li> <li>function to be called can have positional and named arguments</li> <li>You can change <code>interval</code> anytime, it will be effective after next run. Same for <code>args</code>, <code>kwargs</code> and even <code>function</code>!</li> </ul>
3
2016-07-11T22:15:34Z
[ "python", "timer" ]
How do I construct the packets for this UDP protocol?
474,934
<p>Valve Software's Steam Server Query protocol as documented <a href="http://developer.valvesoftware.com/wiki/Server_Queries" rel="nofollow">here</a> allows you to query their game servers for various data. This is a little out of my depth and I'm looking for a little guidance as to what I need to learn.</p> <p>I'm assuming I'll need <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket</a> and <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a>, correct?</p> <p>I'm comfortable with basic UDP tasks like <a href="http://www.prasannatech.net/2008/07/socket-programming-tutorial.html" rel="nofollow">these</a>, so I guess my main question is how do I construct my data with struct, as I'm completely unfamiliar with it.?</p>
0
2009-01-23T22:48:44Z
475,211
<p>I found an answer to my own question. Yay.</p> <p><a href="https://sourceforge.net/projects/srcdspy/" rel="nofollow">SRCDS.py</a> has this implemented already and I figured it out by looking it over.</p>
1
2009-01-24T00:38:19Z
[ "python", "network-programming", "network-protocols" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFFFFFF some_field = (big_num &amp; 0x00FFFF0000000000) # works as expected field_i_need = big_num &amp; 0x00000000FFFFFFFF # doesn't work </code></pre> <p>What happens is that <code>field_i_need</code> is equal to <code>big_num</code>, not the lower 32 bits.</p> <p>Am I missing something simple here?</p> <p>Thanks!</p> <p>Matthew</p>
1
2009-01-23T22:52:18Z
474,963
<p>You need to use long integers.</p> <pre><code>foo = 0xDEADBEEFCAFEBABEL fooLow = foo &amp; 0xFFFFFFFFL </code></pre>
2
2009-01-23T22:55:22Z
[ "python" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFFFFFF some_field = (big_num &amp; 0x00FFFF0000000000) # works as expected field_i_need = big_num &amp; 0x00000000FFFFFFFF # doesn't work </code></pre> <p>What happens is that <code>field_i_need</code> is equal to <code>big_num</code>, not the lower 32 bits.</p> <p>Am I missing something simple here?</p> <p>Thanks!</p> <p>Matthew</p>
1
2009-01-23T22:52:18Z
474,971
<pre><code>&gt;&gt;&gt; big_num = 0xFFFFFFFFFFFFFFFF &gt;&gt;&gt; some_field = (big_num &amp; 0x00FFFF0000000000) # works as expected &gt;&gt;&gt; field_i_need = big_num &amp; 0x00000000FFFFFFFF # doesn't work &gt;&gt;&gt; big_num 18446744073709551615L &gt;&gt;&gt; field_i_need 4294967295L </code></pre> <p>It seems to work, or I am missing the question. I'm using Python 2.6.1, anyway.</p> <p>For your information, I asked a somehow-related <a href="http://stackoverflow.com/questions/210629/python-unsigned-32-bit-bitwise-arithmetic">question</a> some time ago.</p>
4
2009-01-23T22:57:35Z
[ "python" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFFFFFF some_field = (big_num &amp; 0x00FFFF0000000000) # works as expected field_i_need = big_num &amp; 0x00000000FFFFFFFF # doesn't work </code></pre> <p>What happens is that <code>field_i_need</code> is equal to <code>big_num</code>, not the lower 32 bits.</p> <p>Am I missing something simple here?</p> <p>Thanks!</p> <p>Matthew</p>
1
2009-01-23T22:52:18Z
475,229
<p>Obviously, if it's a one-off, then using long integers by appending 'L' to your literals is the quick answer, but for more complicated cases, you might find that you can write clearer code if you look at <a href="http://stackoverflow.com/questions/142812/does-python-have-a-bitfield-type">http://stackoverflow.com/questions/142812/does-python-have-a-bitfield-type</a> since this is how you seem to be using your bitmasks.</p> <p>I think my personal preference would probably be <a href="http://docs.python.org/library/ctypes.html#ctypes-bit-fields-in-structures-unions" rel="nofollow" title="ctypes bit fields">http://docs.python.org/library/ctypes.html#ctypes-bit-fields-in-structures-unions</a> though, since it's in the standard library, and has a pretty clear API.</p>
0
2009-01-24T00:46:27Z
[ "python" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFFFFFF some_field = (big_num &amp; 0x00FFFF0000000000) # works as expected field_i_need = big_num &amp; 0x00000000FFFFFFFF # doesn't work </code></pre> <p>What happens is that <code>field_i_need</code> is equal to <code>big_num</code>, not the lower 32 bits.</p> <p>Am I missing something simple here?</p> <p>Thanks!</p> <p>Matthew</p>
1
2009-01-23T22:52:18Z
481,124
<p>Matthew here, I noticed I had left out one piece of information, I'm using python version 2.2.3. I managed to try this out on another machine w/ version 2.5.1 and everything works as expected. Unfortunately I need to use the older version.</p> <p>Anyway, thank you all for your responses. Appending 'L' seems to do the trick, and this is a one-off so I feel comfortable with this approach.</p> <p>Thanks,</p> <p>Matthew</p>
2
2009-01-26T19:59:33Z
[ "python" ]
Non-ascii string in verbose_name argument when declaring DB field in Django
475,073
<p>I declare this:</p> <pre><code>#This file is using encoding:utf-8 ... class Buddy(models.Model): name=models.CharField('ФИО',max_length=200) ... </code></pre> <p>... in models.py. manage.py syncdb works smoothly. However when I go to admin interface and try to add a new Buddy I catch a DjangoUnicodeDecodeError, which says: "'utf8' codec can't decode bytes in position 0-1: invalid data. You passed in '\xd4\xc8\xce' (&lt;type 'str'&ltr;)".</p> <p>I'm using sqlite3, so all strings are stored as bytestrings encoded in utf8 there. Django's encoding is also utf8. Seen django's docs on this topic, no idea.</p> <p>UPD: Eventually I figured out what the problem was. It turned out to be that I'd saved my source in ANSI encoding.</p> <p>Solution: I saved the source in UTF-8 and it worked wonders.</p>
2
2009-01-23T23:36:31Z
475,207
<p>First, I would explicitly define your description as a Unicode string:</p> <pre><code>class Buddy(models.Model): name=models.CharField(u'ФИО',max_len) </code></pre> <p>Note the 'u' in <code>u'ФИО'</code>.</p> <p>Secondly, do you have a <code>__unicode__()</code> function defined on your model? If so, make sure that it returns a Unicode string. It's very likely you're getting this error when the Admin interface tries to access the unicode representation of the model, not when it's added to the database. If you're returning a non-unicode string from <code>__unicode__()</code>, it may cause this problem.</p>
5
2009-01-24T00:37:48Z
[ "python", "django", "unicode" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to release more apps with it. One thing that I wonder about is the possibility of people circumventing any licensing code I put in, or being able to just rip off my entire source base. I've heard of Py2Exe and similar applications, but I'm curious if there are 'preferred' ways of doing it, or if this problem is just a fact of life.</p>
6
2009-01-24T00:40:09Z
475,246
<p>Security through obscurity <em>never</em> works. If you must use a proprietary license, enforce it through the law, not half-baked obfuscation attempts.</p> <p>If you're worried about them learning your security (e.g. cryptography) algorithm, the same applies. Real, useful, security algorithms (like AES) are secure even though the algorithm is fully known.</p>
12
2009-01-24T00:56:39Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to release more apps with it. One thing that I wonder about is the possibility of people circumventing any licensing code I put in, or being able to just rip off my entire source base. I've heard of Py2Exe and similar applications, but I'm curious if there are 'preferred' ways of doing it, or if this problem is just a fact of life.</p>
6
2009-01-24T00:40:09Z
475,269
<p>The word you're looking for is obfuscate. A quick google reveals:</p> <p><a href="http://www.lysator.liu.se/~astrand/projects/pyobfuscate/" rel="nofollow">http://www.lysator.liu.se/~astrand/projects/pyobfuscate/</a></p> <p>but:</p> <p>a) If copyright infringement becomes a problem, then the law is on your side (as long as you include the appropriate copyright notices in all files).</p> <p>b) It's also possible to make a profit on open source applications if you're clever about it.</p> <p>c) If you want your Intellectual Property to be truly secure, then the only answer is to not let anyone have it in the first place: Write your application as a web app, (I recommend using django) and only your web hosting provider has access to your code.</p>
3
2009-01-24T01:12:13Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to release more apps with it. One thing that I wonder about is the possibility of people circumventing any licensing code I put in, or being able to just rip off my entire source base. I've heard of Py2Exe and similar applications, but I'm curious if there are 'preferred' ways of doing it, or if this problem is just a fact of life.</p>
6
2009-01-24T00:40:09Z
475,394
<p>Even if you use a compiled language like C# or Java, people can perform reverse engineering if they are motivated and technically competent. Obfuscation is not a reliable protection against this.</p> <p>You can add prohibition against reverse-engineering to your end-user license agreement for your software. Most proprietary companies do this. But that doesn't prevent violation, it only gives you legal recourse.</p> <p>The <em>best</em> solution is to offer products and services in which the user's access to read your code does not harm your ability to sell your product or service. Base your business on service provided, or subscription to periodic updates to data, rather than the code itself.</p> <p>Example: Slashdot actually makes their code for their website available. Does this harm their ability to run their website? No.</p> <p>Another remedy is to set your price point such that the effort to pirate your code is more costly than simply buying legitimate licenses to use your product. Joel Spolsky has made a recommendation to this effects in his articles and podcasts.</p>
7
2009-01-24T03:02:04Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to release more apps with it. One thing that I wonder about is the possibility of people circumventing any licensing code I put in, or being able to just rip off my entire source base. I've heard of Py2Exe and similar applications, but I'm curious if there are 'preferred' ways of doing it, or if this problem is just a fact of life.</p>
6
2009-01-24T00:40:09Z
476,094
<p>Shipping a <a href="http://www.checkoutapp.com">commercial mac desktop app</a> in Python, we do exactly as described in the other answers; protect yourself by law with a decent EULA, not by obfuscating. </p> <p>We have never had any troubles with people reverse engineering our code. And if we do, I feel confident we can take legal action. So yes, it's a fact of life. But one that is not too hard to live with. Just get a decent lawyer that writes a decent EULA.</p>
5
2009-01-24T14:43:27Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to release more apps with it. One thing that I wonder about is the possibility of people circumventing any licensing code I put in, or being able to just rip off my entire source base. I've heard of Py2Exe and similar applications, but I'm curious if there are 'preferred' ways of doing it, or if this problem is just a fact of life.</p>
6
2009-01-24T00:40:09Z
534,314
<p><strong>py2exe</strong></p> <p>On windows py2exe is one way of shipping code to end-users, py2exe bundles the python interpreter, the necessary dlls and your code compiled to python bytecode. </p> <p>Here are the python bytecode instructions to get some clue what it looks like:</p> <p><a href="http://www.python.org/doc/2.5.2/lib/bytecodes.html" rel="nofollow">http://www.python.org/doc/2.5.2/lib/bytecodes.html</a></p> <p>Or you can use <strong>dis</strong> to disassemble some pyc/pyo files.</p> <p>So, using py2exe is similar to distributing compiled python (pyc/pyo) files.</p> <p><strong>Shedskin C++ compiler</strong></p> <p>The Shedskin compiler compiles a subset of python to C++ which you can compile to native code using any compiler.</p> <p><strong>pypy</strong></p> <p>I don't know about PyPy too much. According to their docs Pypy is able to generate C code.</p>
1
2009-02-10T21:35:29Z
[ "python", "security", "reverse-engineering" ]
PostgreSQL procedural languages: to choose?
475,302
<p>I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manually. </p> <p>I would run my python script on my 32bit laptop and have it communicate with a $6000 64bit server running PostgreSQL; I would hence have an extra 2.10 Ghz, 3 GB of RAM, psyco and a multithreaded SQL query manager.</p> <p>I now realize that it is time for me to level up. I need to learn to server-side script using a procedural language (PL); I really need to reduce network traffic and its inherent serializing overhead. </p> <p>Now, I really do not feel like researching all the PLs. Knowing that I already know python, and that I am looking for the means between effort and language efficiency, what PL do you guys fancy I should install, learn and use, and why and how?</p>
2
2009-01-24T01:38:35Z
475,334
<p>Since you already known python, PL/Python should be something to look at. And you sound like you write SQL for your database queries, so PL/SQL is a natural extension of that.</p> <p>PL/SQL feels like SQL, just with all the stuff that you would expect from SQL anyway, like variables for whole rows and the usual control structures of procedural languages. It fits the way you usually interact with the database, but it's not the most elegant language of all time. I can't say anything about PL/Python, since I have never used it, but since you know python it should be easy to flip through <a href="http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html">some examples</a> and see if you like it.</p>
5
2009-01-24T02:02:11Z
[ "python", "postgresql" ]
PostgreSQL procedural languages: to choose?
475,302
<p>I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manually. </p> <p>I would run my python script on my 32bit laptop and have it communicate with a $6000 64bit server running PostgreSQL; I would hence have an extra 2.10 Ghz, 3 GB of RAM, psyco and a multithreaded SQL query manager.</p> <p>I now realize that it is time for me to level up. I need to learn to server-side script using a procedural language (PL); I really need to reduce network traffic and its inherent serializing overhead. </p> <p>Now, I really do not feel like researching all the PLs. Knowing that I already know python, and that I am looking for the means between effort and language efficiency, what PL do you guys fancy I should install, learn and use, and why and how?</p>
2
2009-01-24T01:38:35Z
475,939
<p>Why can't you run your Python on the database server? That has the fewest complexities -- you can run the program you already have.</p>
2
2009-01-24T12:13:14Z
[ "python", "postgresql" ]
PostgreSQL procedural languages: to choose?
475,302
<p>I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manually. </p> <p>I would run my python script on my 32bit laptop and have it communicate with a $6000 64bit server running PostgreSQL; I would hence have an extra 2.10 Ghz, 3 GB of RAM, psyco and a multithreaded SQL query manager.</p> <p>I now realize that it is time for me to level up. I need to learn to server-side script using a procedural language (PL); I really need to reduce network traffic and its inherent serializing overhead. </p> <p>Now, I really do not feel like researching all the PLs. Knowing that I already know python, and that I am looking for the means between effort and language efficiency, what PL do you guys fancy I should install, learn and use, and why and how?</p>
2
2009-01-24T01:38:35Z
476,089
<p>I was in the exact same situation as you and went with PL/Python after giving up on PL/SQL after a while. It was a good decision, looking back. Some things that bit me where unicode issues (client encoding, byte sequence) and specific postgres data types (bytea).</p>
1
2009-01-24T14:34:25Z
[ "python", "postgresql" ]
group by in django
475,552
<p>How can i create simple group by query in trunk version of django?</p> <p>I need something like</p> <pre><code>SELECT name FROM mytable GROUP BY name </code></pre> <p>actually what i want to do is simply get all entries with distinct names. </p>
3
2009-01-24T05:15:15Z
475,664
<p>Add .distinct to your queryset:</p> <pre><code>Entries.objects.filter(something='xxx').distinct() </code></pre>
3
2009-01-24T07:04:07Z
[ "python", "django", "django-models" ]
group by in django
475,552
<p>How can i create simple group by query in trunk version of django?</p> <p>I need something like</p> <pre><code>SELECT name FROM mytable GROUP BY name </code></pre> <p>actually what i want to do is simply get all entries with distinct names. </p>
3
2009-01-24T05:15:15Z
475,670
<p>this will not work because every row have unique id. So every record is distinct.. </p> <p>To solve my problem i used </p> <pre><code>foo = Foo.objects.all() foo.query.group_by = ['name'] </code></pre> <p>but this is not official API.</p>
2
2009-01-24T07:09:16Z
[ "python", "django", "django-models" ]