title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
306,377
<p>It depends on whether you're looking to see if 2 things are equal, or the same object. </p> <p>"is" checks to see if they are the same object, not just equal. The small ints are probably pointing to the same memory location for space efficiency </p> <pre><code>In [29]: a = 3 In [30]: b = 3 In [31]: id(a) Out[31]: 500729144 In [32]: id(b) Out[32]: 500729144 </code></pre> <p>You should use "==" to compare equality of arbitrary objects. You can specify the behavior with the <code>__eq__</code>, and <code>__ne__</code> attributes.</p>
46
2008-11-20T18:36:06Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
306,603
<p>As you can check in <a href="http://svn.python.org/projects/python/trunk/Objects/intobject.c">source file <em>intobject.c</em></a>, Python caches small integers for efficiency. Every time you create a reference to a small integer, you are referring the cached small integer, not a new object. 257 is not an small integer, so it is calculated as a different object.</p> <p>It is better to use "==" for that purpose.</p>
29
2008-11-20T19:50:11Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
307,594
<p>For immutable value objects, like ints, strings or datetimes, object identity is not especially useful. It's better to think about equality. Identity is essentially an implementation detail for value objects - since they're immutable, there's no effective difference between having multiple refs to the same object or multiple objects.</p>
10
2008-11-21T01:58:53Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
15,522,094
<p><code>is</code> <em>is</em> the identity equality operator (functioning like <code>id(a) == id(b)</code>); it's just that two equal numbers aren't necessarily the same object. For performance reasons some small integers happen to be <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoized</a> so they will tend to be the same (this can be done since they are immutable).</p> <p><a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP's</a> <code>===</code> operator, on the other hand, is described as checking equality and type: <code>x == y and type(x) == type(y)</code> as per Paulo Freitas' comment. This will suffice for common numbers, but differ from <code>is</code> for classes that define <code>__eq__</code> in an absurd manner:</p> <pre><code>class Unequal: def __eq__(self, other): return False </code></pre> <p>PHP apparently allows the same thing for "built-in" classes (which I take to mean implemented at C level, not in PHP). A slightly less absurd use might be a timer object, which has a different value every time it's used as a number. Quite why you'd want to emulate Visual Basic's <code>Now</code> instead of showing that it is an evaluation with <code>time.time()</code> I don't know.</p> <p>Greg Hewgill (OP) made one clarifying comment "My goal is to compare object identity, rather than equality of value. Except for numbers, where I want to treat object identity the same as equality of value."</p> <p>This would have yet another answer, as we have to categorize things as numbers or not, to select whether we compare with <code>==</code> or <code>is</code>. <a href="http://en.wikipedia.org/wiki/CPython" rel="nofollow">CPython</a> defines the <a href="http://docs.python.org/2/c-api/number.html" rel="nofollow">number protocol</a>, including PyNumber_Check, but this is not accessible from Python itself.</p> <p>We could try to use <code>isinstance</code> with all the number types we know of, but this would inevitably be incomplete. The types module contains a StringTypes list but no NumberTypes. Since Python 2.6, the built in number classes have a base class <a href="https://docs.python.org/2/library/numbers.html#numbers.Number" rel="nofollow"><code>numbers.Number</code></a>, but it has the same problem:</p> <pre><code>import numpy, numbers assert not issubclass(numpy.int16,numbers.Number) assert issubclass(int,numbers.Number) </code></pre> <p>By the way, <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> will produce separate instances of low numbers.</p> <p>I don't actually know an answer to this variant of the question. I suppose one could theoretically use ctypes to call <code>PyNumber_Check</code>, but even that function <a href="http://mail.python.org/pipermail/python-dev/2002-November/030237.html" rel="nofollow">has been debated</a>, and it's certainly not portable. We'll just have to be less particular about what we test for now.</p> <p>In the end, this issue stems from Python not originally having a type tree with predicates like <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="nofollow">Scheme's</a> <code>number?</code>, or <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="nofollow">Haskell's</a> <a href="https://en.wikipedia.org/wiki/Type_class" rel="nofollow">type class</a> <a href="http://www.haskell.org/ghc/docs/7.4-latest/html/libraries/base-4.5.1.0/Prelude.html#t:Num" rel="nofollow">Num</a>. <code>is</code> checks object identity, not value equality. PHP has a colorful history as well, where <code>===</code> apparently behaves as <code>is</code> only on objects <a href="http://www.php.net/manual/en/language.operators.comparison.php" rel="nofollow">in PHP5, but not PHP4</a>. Such are the growing pains of moving across languages (including versions of one).</p>
7
2013-03-20T11:20:46Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
28,864,111
<blockquote> <h1>Python's “is” operator behaves unexpectedly with integers?</h1> </blockquote> <p>Let me emphasize: <strong><em>Do not use <code>is</code> to compare integers.</em></strong></p> <p>This isn't behavior you should have any expectations about.</p> <p>Instead, use <code>==</code> and <code>!=</code> to compare for equality and inequality, respectively.</p> <p>To know this, you need to know the following.</p> <p>First, what does <code>is</code> do? It is a comparison operator. From the <a href="https://docs.python.org/2/reference/expressions.html#not-in" rel="nofollow">documentation</a>:</p> <blockquote> <p>The operators <code>is</code> and <code>is not</code> test for object identity: <code>x is y</code> is true if and only if x and y are the same object. <code>x is not y</code> yields the inverse truth value.</p> </blockquote> <p>And so the following are equivalent. </p> <pre><code>&gt;&gt;&gt; a is b &gt;&gt;&gt; id(a) == id(b) </code></pre> <p>From the <a href="https://docs.python.org/library/functions.html#id" rel="nofollow">documentation</a>:</p> <blockquote> <p><strong><code>id</code></strong> Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same <code>id()</code> value.</p> </blockquote> <p>Note that the fact that the id of an object in CPython (the reference implementation of Python) is the location in memory is an implementation detail. Other implementations of Python (such as Jython or IronPython) could easily have a different implementation for <code>id</code>.</p> <p>So what is the use-case for <code>is</code>? <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations" rel="nofollow">PEP8 describes</a>:</p> <blockquote> <p>Comparisons to singletons like None should always be done with is or is not , never the equality operators.</p> </blockquote> <h1>The Question</h1> <p>You ask, and state, the following question (with code):</p> <blockquote> <p><strong>Why does the following behave unexpectedly in Python?</strong></p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result </code></pre> </blockquote> <p>It is <em>not</em> an expected result. Why is it expected? It only means that the integers valued at <code>256</code> referenced by both <code>a</code> and <code>b</code> are the same instance of integer. Integers are immutable in Python, thus they cannot change. This should have no impact on any code. It should not be expected. It is merely an implementation detail. </p> <p>But perhaps we should be glad that there is not a new separate instance in memory every time we state a value equals 256. </p> <blockquote> <pre><code>&gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? </code></pre> </blockquote> <p>Looks like we now have two separate instances of integers with the value of <code>257</code> in memory. Since integers are immutable, this wastes memory. Let's hope we're not wasting a lot of it. We're probably not. But this behavior is not guaranteed.</p> <blockquote> <pre><code>&gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> </blockquote> <p>Well, this looks like your particular implementation of Python is trying to be smart and not creating redundantly valued integers in memory unless it has to. You seem to indicate you are using the referent implementation of Python, which is CPython. Good for CPython. </p> <p>It might be even better if CPython could do this globally, if it could do so cheaply (as there would a cost in the lookup), perhaps another implementation might. </p> <p>But as for impact on code, you should not care if an integer is a particular instance of an integer. You should only care what the value of that instance is, and you would use the normal comparison operators for that, i.e. <code>==</code>.</p> <h2>What <code>is</code> does</h2> <p><code>is</code> checks that the <code>id</code> of two objects are the same. In CPython, the <code>id</code> is the location in memory, but it could be some other uniquely identifying number in another implementation. To restate this with code:</p> <pre><code>&gt;&gt;&gt; a is b </code></pre> <p>is the same as</p> <pre><code>&gt;&gt;&gt; id(a) == id(b) </code></pre> <h2>Why would we want to use <code>is</code> then?</h2> <p>This can be a very fast check relative to say, checking if two very long strings are equal in value. But since it applies to the uniqueness of the object, we thus have limited use-cases for it. In fact, we mostly want to use it to check for <code>None</code>, which is a singleton (a sole instance existing in one place in memory). We might create other singletons if there is potential to conflate them, which we might check with <code>is</code>, but these are relatively rare. Here's an example (will work in Python 2 and 3) e.g.</p> <pre><code>SENTINEL_SINGLETON = object() # this will only be created one time. def foo(keyword_argument=None): if keyword_argument is None: print('no argument given to foo') bar() bar(keyword_argument) bar('baz') def bar(keyword_argument=SENTINEL_SINGLETON): # SENTINEL_SINGLETON tells us if we were not passed anything # as None is a legitimate potential argument we could get. if keyword_argument is SENTINEL_SINGLETON: print('no argument given to bar') else: print('argument to bar: {0}'.format(keyword_argument)) foo() </code></pre> <p>Which prints:</p> <pre><code>no argument given to foo no argument given to bar argument to bar: None argument to bar: baz </code></pre> <p>And so we see, with <code>is</code> and a sentinel, we are able to differentiate between when <code>bar</code> is called with no arguments and when it is called with <code>None</code>. These are the primary use-cases for <code>is</code> - do <em>not</em> use it to test for equality of integers, strings, tuples, or other things like these.</p>
19
2015-03-04T20:20:12Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
33,130,014
<p>It also happens with strings:</p> <pre><code>&gt;&gt;&gt; s = b = 'somestr' &gt;&gt;&gt; s == b, s is b, id(s), id(b) (True, True, 4555519392, 4555519392) </code></pre> <p>Now everything seems fine.</p> <pre><code>&gt;&gt;&gt; s = 'somestr' &gt;&gt;&gt; b = 'somestr' &gt;&gt;&gt; s == b, s is b, id(s), id(b) (True, True, 4555519392, 4555519392) </code></pre> <p>That's expected too.</p> <pre><code>&gt;&gt;&gt; s1 = b1 = 'somestrdaasd ad ad asd as dasddsg,dlfg ,;dflg, dfg a' &gt;&gt;&gt; s1 == b1, s1 is b1, id(s1), id(b1) (True, True, 4555308080, 4555308080) &gt;&gt;&gt; s1 = 'somestrdaasd ad ad asd as dasddsg,dlfg ,;dflg, dfg a' &gt;&gt;&gt; b1 = 'somestrdaasd ad ad asd as dasddsg,dlfg ,;dflg, dfg a' &gt;&gt;&gt; s1 == b1, s1 is b1, id(s1), id(b1) (True, False, 4555308176, 4555308272) </code></pre> <p>Now that's unexpected.</p>
3
2015-10-14T15:53:05Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
34,964,030
<h3><em>I'm late but, you want some of that good source with your answer?</em><sup>*</sup></h3> <p>Good thing about Python is that you can actually see the source for this. I'm going to use Python 3.5 links for now; finding the corresponding <code>2.x</code> ones is trivial.</p> <p>In Python, <code>int</code> objects are actually (<em><a href="https://www.python.org/dev/peps/pep-0237/">unified some time ago</a></em>) of <code>c</code> <code>long</code> type. The dedicated Python <code>C-API</code> function that handles creating a new <code>int</code> object is <a href="https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong"><code>PyLong_FromLong(long v)</code></a>. The description for this function is:</p> <blockquote> <p><em>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object</em>. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)</p> </blockquote> <p>Don't know about you but I see this and think:</p> <h3><em>Let's find that array!</em></h3> <p>If you haven't fiddled with the <code>C</code> code implementing Python <em>you should</em>, everything is pretty organized and readable. For our case, we need to look in the <a href="https://hg.python.org/cpython/file/d489394a73de/Objects/"><code>Objects/</code> subdirectory</a> of the <a href="https://hg.python.org/cpython/file/tip">main source code directory tree</a>.</p> <p><code>PyLong_FromLong</code> deals with <code>long</code> objects so it shouldn't be hard to deduce that we need to peek inside <a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c"><code>longobject.c</code></a>. After looking inside you might think things are chaotic; they are, but fear not, the function we're looking for is chilling at <a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c#l230"><code>line 230</code></a> waiting for us to check it out. It's a smallish function so the main body (excluding declarations) is easily pasted here:</p> <pre><code>PyObject * PyLong_FromLong(long ival) { // omitting declarations CHECK_SMALL_INT(ival); if (ival &lt; 0) { /* negate: cant write this as abs_ival = -ival since that invokes undefined behaviour when ival is LONG_MIN */ abs_ival = 0U-(unsigned long)ival; sign = -1; } else { abs_ival = (unsigned long)ival; } /* Fast path for single-digit ints */ if (!(abs_ival &gt;&gt; PyLong_SHIFT)) { v = _PyLong_New(1); if (v) { Py_SIZE(v) = sign; v-&gt;ob_digit[0] = Py_SAFE_DOWNCAST( abs_ival, unsigned long, digit); } return (PyObject*)v; } </code></pre> <p>Now, we're no <code>C</code> <em>master-code-haxxorz</em> but we're also not dumb, we can see that <code>CHECK_SMALL_INT(ival);</code> peeking at us all seductively; we can understand it has something to do with this. <a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c#l51">Let's check it out:</a></p> <pre><code>#define CHECK_SMALL_INT(ival) \ do if (-NSMALLNEGINTS &lt;= ival &amp;&amp; ival &lt; NSMALLPOSINTS) { \ return get_small_int((sdigit)ival); \ } while(0) </code></pre> <p>So it's a macro that calls function <code>get_small_int</code> if the value <code>ival</code> satisfies the condition:</p> <pre><code>if (-NSMALLNEGINTS &lt;= ival &amp;&amp; ival &lt; NSMALLPOSINTS) </code></pre> <p>So what are <code>NSMALLNEGINTS</code> and <code>NSMALLPOSINTS</code>? If you guessed macros you get nothing because that wasn't such a hard question.. <em><a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c#l12">Anyway, here they are</a></em>:</p> <pre><code>#ifndef NSMALLPOSINTS #define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS #define NSMALLNEGINTS 5 #endif </code></pre> <p>So our condition is <code>if (-5 &lt;= ival &amp;&amp; ival &lt; 257)</code> call <code>get_small_int</code>. </p> <p>No other place to go but continue our journey by looking at <a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c#l37"><code>get_small_int</code> in all its glory</a> (well, we'll just look at it's body because that's were the interesting things are):</p> <pre><code>PyObject *v; assert(-NSMALLNEGINTS &lt;= ival &amp;&amp; ival &lt; NSMALLPOSINTS); v = (PyObject *)&amp;small_ints[ival + NSMALLNEGINTS]; Py_INCREF(v); </code></pre> <p>Okay, create a <code>PyObject</code>, assert that the previous condition holds and execute the assignment:</p> <pre><code>v = (PyObject *)&amp;small_ints[ival + NSMALLNEGINTS]; </code></pre> <p><code>small_ints</code> looks a lot like that array we've been searching for.. and, it is! <em><a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c#l25">We could've just read the damn documentation and we would've know all along!</a></em>:</p> <pre><code>/* Small integers are preallocated in this array so that they can be shared. The integers that are preallocated are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */ static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS]; </code></pre> <p>So yup, this is our guy. When you want to create a new <code>int</code> in the range <code>[NSMALLNEGINTS, NSMALLPOSINTS)</code> you'll just get back a reference to an already existing object that has been preallocated. </p> <p>Since the reference refers to the same object issuing <code>id()</code> directly or checking for identity with <code>is</code> on it will return exactly the same thing. </p> <h3>But, when are they allocated??</h3> <p><a href="https://hg.python.org/cpython/file/tip/Objects/longobject.c#l5343">During initialization in <code>_PyLong_Init</code></a> Python will gladly enter in a for loop do do this for you: </p> <pre><code>for (ival = -NSMALLNEGINTS; ival &lt; NSMALLPOSINTS; ival++, v++) { // Look me up! } </code></pre> <p>I hope my explanation has made you <code>C</code> (common pun) things clearly now.</p> <hr> <h3>But, 257 is 257? What's up?</h3> <p>This is actually easier to explain, <a href="http://stackoverflow.com/questions/34147515/is-operator-returns-different-results-on-integers">and I have attempted to do so already</a>; it's due to the fact that Python will execute this interactive statement:</p> <pre><code>&gt;&gt;&gt; 257 is 257 </code></pre> <p>In its own execution frame. When constructing this frame Python will see that you have two matching literals and will use the same <code>PyLongObject</code> representing <code>257</code>. You can see this if you do the compilation yourself and examine its contents:</p> <pre><code>&gt;&gt;&gt; codeObj = compile("257 is 257", "blah!", "exec") &gt;&gt;&gt; codeObj.co_consts (257, None) </code></pre> <p>When Python does the operation; it's now just going to load the exact same object:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(codeObj) 1 0 LOAD_CONST 0 (257) # dis 3 LOAD_CONST 0 (257) # dis again 6 COMPARE_OP 8 (is) </code></pre> <p>So <code>is</code> will return <code>True</code>.</p> <hr> <p><sub>* -- I'll try and word this in a more introductory manner in order for most to be able to follow along.</sub></p>
6
2016-01-23T13:26:00Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
35,481,897
<p>Take a look <a href="https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong" rel="nofollow">here</a></p> <blockquote> <p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.</p> </blockquote>
3
2016-02-18T12:46:27Z
[ "python", "int", "comparison", "operators", "identity" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
306,417
<p>Use <a href="https://docs.python.org/2/library/random.html#random.choice"><code>random.choice</code></a>:</p> <pre><code>import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) </code></pre>
1,462
2008-11-20T18:46:39Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
12,373,205
<p>In case you also need the index:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] from random import randrange random_index = randrange(0,len(foo)) print foo[random_index] </code></pre>
63
2012-09-11T15:31:16Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
14,015,085
<p>if you need the index just use:</p> <pre><code>import random foo = ['a', 'b', 'c', 'd', 'e'] print int(random.random() * len(foo)) print foo[int(random.random() * len(foo))] </code></pre> <p>random.choice does the same:)</p>
2
2012-12-23T22:06:36Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
16,514,203
<p>I propose a script for removing randomly picked up items off a list until it is empty:</p> <p>Maintain a <code>set</code> and remove randomly picked up element (with <code>choice</code>) until list is empty.</p> <pre><code>s=set(range(1,6)) import random while len(s)&gt;0: s.remove(random.choice(list(s))) print(s) </code></pre> <p>Three runs give three different answers:</p> <pre><code>&gt;&gt;&gt; set([1, 3, 4, 5]) set([3, 4, 5]) set([3, 4]) set([4]) set([]) &gt;&gt;&gt; set([1, 2, 3, 5]) set([2, 3, 5]) set([2, 3]) set([2]) set([]) &gt;&gt;&gt; set([1, 2, 3, 5]) set([1, 2, 3]) set([1, 2]) set([1]) set([]) </code></pre>
14
2013-05-13T02:47:36Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
19,064,832
<pre><code>import random_necessary pick = ['Miss','Mrs','MiSs','Miss'] print pick [int(random_necessary.random_necessary() * len(pick))] </code></pre> <p>hope this may find the solution.</p>
-7
2013-09-28T08:09:33Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
21,515,484
<p>i had to do this:</p> <p><code>import random</code></p> <p><code>pick = ['Random','Random1','Random2','Random3']</code></p> <p><code>print (pick[int(random.random() * len(pick))])</code></p>
-4
2014-02-02T20:00:04Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
25,133,330
<p>We can also do this using randint.</p> <pre><code>from random import randint l= ['a','b','c'] def get_rand_element(l): if l: return l[randint(0,len(l)-1)] else: return None get_rand_element(l) </code></pre>
0
2014-08-05T07:28:08Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
30,441,100
<p>This is the code with a variable that defines the random index:</p> <pre><code>import random foo = ['a', 'b', 'c', 'd', 'e'] randomindex = random.randint(0,len(foo)-1) print (foo[randomindex]) ## print (randomindex) </code></pre> <p>This is the code without the variable:</p> <pre><code>import random foo = ['a', 'b', 'c', 'd', 'e'] print (foo[random.randint(0,len(foo)-1)]) </code></pre> <p>And this is the code in the shortest and smartest way to do it:</p> <pre><code>import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) </code></pre> <p>(python 2.7)</p>
2
2015-05-25T14:57:25Z
[ "python", "list", "random" ]
How do I randomly select an item from a list using Python?
306,400
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
824
2008-11-20T18:42:21Z
30,488,952
<p>If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using <code>random.sample</code> instead.</p> <pre><code>import random group_of_items = {1, 2, 3, 4} # a sequence or set will work here. num_to_select = 2 # set the number to select here. list_of_random_items = random.sample(group_of_items, num_to_select) first_random_item = list_of_random_items[0] second_random_item = list_of_random_items[1] </code></pre> <p>If you're only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax <code>random.sample(some_list, 1)[0]</code> instead of <code>random.choice(some_list)</code>.</p> <p>Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though <code>random.choice(tuple(some_set))</code> may be an option for getting a single item from a set.</p>
34
2015-05-27T17:07:07Z
[ "python", "list", "random" ]
How can I get a list of the running applications with GTK?
306,456
<p>How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen.</p>
0
2008-11-20T19:02:27Z
306,866
<p>The panel you are referring to is the GNOME panel. So this is a GNOME question, not a GTK question.</p> <p>There is not a well-defined concept of "multi-window application" in GNOME that I know of. The panel task list is probably build by querying the window manager for the list of windows and grouping the windows by their "class" property.</p> <p>There are also various window manager hints that must be taken into account, for example to ignore panels and other utility windows. In your place, I would look at the source code of the taskbar applet. There is maybe some documentation somewhere that covers the status-quo, but I do know where it would be.</p>
0
2008-11-20T21:12:51Z
[ "python", "gtk", "pygtk" ]
How can I get a list of the running applications with GTK?
306,456
<p>How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen.</p>
0
2008-11-20T19:02:27Z
307,046
<p>I believe what you are looking for is libwnck</p>
2
2008-11-20T22:13:36Z
[ "python", "gtk", "pygtk" ]
With Python, how can I ensure that compression of a folder takes place within a particular folder?
306,811
<p>I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my "test.zip" file to be contained in C:\test. How can I do this? Thanks in advance.</p> <p><strong><em>clarification of question with code example:</em></strong></p> <p>Someone kindly pointed out that my question is confusing, but for a python newbie a lot of things are confusing :) - my advance apologies if this question is too basic or the answer is obvious. I don't know how I can ensure that the resulting zip file is inside the folder that has been zipped. In other words, I would like the zip process to take place in 'basedir.' That way the user does not waste time searching for it somewhere on the C drive.</p> <p><pre><code><br /> def zip_folder(basedir, zip_file): z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(basedir): print "zipping files:" for fn in filenames: print fn absfn = os.path.join(dirpath, fn) z.write(absfn) z.close </pre></code></p>
0
2008-11-20T20:47:28Z
307,091
<p>Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zip_file is an absolute path.</p>
1
2008-11-20T22:23:49Z
[ "python", "file", "zip" ]
How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?
306,901
<p>When I run a wxPython application, it prints the string &ldquo;Redirecting output to win32trace remote collector&rdquo;and I must open PythonWin's trace collector tool to view that trace output.</p> <p>Since I'm not interested in collecting this output, how should I disable this feature?</p>
1
2008-11-20T21:26:35Z
306,925
<p>This message deceived me into thinking win32trace was preventing me from seeing uncaught exceptions in the regular console (of my IDE). The real issue was that wxPython by default redirects stdout/stderr to a popup window that quickly disappeared after an uncaught exception. To solve <em>that</em> problem, I simply had to pass <pre>redirect=0</pre> to the superclass constructor of my application.</p> <pre><code>class MyApp(wx.App): def __init__(self): # Prevent wxPython from redirecting stdout/stderr: super(MyApp, self).__init__(redirect=0) </code></pre> <p>That fix notwithstanding, I am still curious about how to control win32trace.</p>
1
2008-11-20T21:34:17Z
[ "python", "windows", "wxpython" ]
How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?
306,901
<p>When I run a wxPython application, it prints the string &ldquo;Redirecting output to win32trace remote collector&rdquo;and I must open PythonWin's trace collector tool to view that trace output.</p> <p>Since I'm not interested in collecting this output, how should I disable this feature?</p>
1
2008-11-20T21:26:35Z
306,936
<p>You can even pass that when you instantiate your wx.App():</p> <pre><code>if __name__ == "__main__": app = wx.App(redirect=False) #or 0 app.MainLoop() </code></pre> <p><a href="http://wxpython.org/docs/api/wx.App-class.html#__init__" rel="nofollow">wxPython wx.App docs</a></p>
2
2008-11-20T21:38:55Z
[ "python", "windows", "wxpython" ]
How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?
306,901
<p>When I run a wxPython application, it prints the string &ldquo;Redirecting output to win32trace remote collector&rdquo;and I must open PythonWin's trace collector tool to view that trace output.</p> <p>Since I'm not interested in collecting this output, how should I disable this feature?</p>
1
2008-11-20T21:26:35Z
1,160,098
<p>It seems to be an Problem with <a href="http://mercurial.selenic.com/bts/issue969" rel="nofollow">TortoiseHG</a>. It also happens when using win32gui.GetOpenFileNameW. Uninstalling solves this problem. Unfortunately i found no real solution how to fix this.</p>
1
2009-07-21T15:51:39Z
[ "python", "windows", "wxpython" ]
Django foreign key access in save() function
307,038
<p>Here's my code:</p> <pre>class Publisher(models.Model): name = models.CharField( max_length = 200, unique = True, ) url = models.URLField() def __unicode__(self): return self.name def save(self): pass class Item(models.Model): publisher = models.ForeignKey(Publisher) name = models.CharField( max_length = 200, ) code = models.CharField( max_length = 10, ) def __unicode__(self): return self.name</pre> <p>I want to be able to access each Item from the Publisher save function. How can I do this?</p> <p>For instance, I'd like to append text to the "code" field of each Item associated with this Publisher on the save of Publisher.</p> <p><b>edit</b>: When I try to implement the first solution, I get the error "'Publisher' object has no attribute 'item_set'". Apparently I can't access it that way. Any other clues?</p> <p><b>edit 2</b>: I discovered that the problem occurring is that when I create a new Publisher object, I add Items inline. Therefor, when trying to save a Publisher and access the Items, they don't exist.</p> <p>Is there any way around this?!</p>
2
2008-11-20T22:10:21Z
307,099
<p>You should be able to do something like the following:</p> <pre><code>def save(self, **kwargs): super(Publisher, self).save(**kwargs) for item in self.item_set.all(): item.code = "%s - whatever" % item.code </code></pre> <p>I don't really like what you're doing here, this isn't a good way to relate <code>Item</code> to <code>Publisher</code>. What is it you're after in the end?</p>
6
2008-11-20T22:25:09Z
[ "python", "django", "django-models" ]
Create plugins for python standalone executables
307,338
<p>how to create a good plugin engine for standalone executables created with pyInstaller, py2exe or similar tools? </p> <p>I do not have experience with py2exe, but pyInstaller uses an import hook to import packages from it's compressed repository. Of course I am able to import dynamically another compressed repository created with pyInstaller and execute the code - this may be a simple plugin engine.</p> <p>Problems appears when the plugin (this what is imported dynamically) uses a library that is not present in original repository (never imported). This is because import hook is for the original application and searches for packages in original repository - not the one imported later (plugin package repository). </p> <p>Is there an easy way to solve this problem? Maybe there exist such engine?</p>
4
2008-11-20T23:55:52Z
307,517
<p>When compiling to exe, your going to have this issue.</p> <p>The only option I can think of to allow users access with thier plugins to use any python library is to include all libraries in the exe package. </p> <p>It's probably a good idea to limit supported libraries to a subset, and list it in your documentation. Up to you.</p> <p>I've only used py2exe.</p> <p>In py2exe you can specify libraries that were not found in the search in the <strong>setup.py</strong> file.</p> <p>Here's a sample:</p> <pre><code>from distutils.core import setup import py2exe setup (name = "script2compile", console=['script2compile.pyw'], version = "1.4", author = "me", author_email="[email protected]", url="myurl.com", windows = [{ "script":"script2compile.pyw", "icon_resources":[(1,"./ICONS/app.ico")] # Icon file to use for display }], # put packages/libraries to include in the "packages" list options = {"py2exe":{"packages": [ "pickle", "csv", "Tkconstants", "Tkinter", "tkFileDialog", "pyexpat", "xml.dom.minidom", "win32pdh", "win32pdhutil", "win32api", "win32con", "subprocess", ]}} ) import win32pdh import win32pdhutil import win32api </code></pre>
2
2008-11-21T01:17:47Z
[ "python", "plugins", "py2exe", "pyinstaller" ]
Create plugins for python standalone executables
307,338
<p>how to create a good plugin engine for standalone executables created with pyInstaller, py2exe or similar tools? </p> <p>I do not have experience with py2exe, but pyInstaller uses an import hook to import packages from it's compressed repository. Of course I am able to import dynamically another compressed repository created with pyInstaller and execute the code - this may be a simple plugin engine.</p> <p>Problems appears when the plugin (this what is imported dynamically) uses a library that is not present in original repository (never imported). This is because import hook is for the original application and searches for packages in original repository - not the one imported later (plugin package repository). </p> <p>Is there an easy way to solve this problem? Maybe there exist such engine?</p>
4
2008-11-20T23:55:52Z
955,948
<p>PyInstaller <em>does</em> have a plugin system for handling hidden imports, and ships with several of those already in. See the webpage (<a href="http://www.pyinstaller.org" rel="nofollow">http://www.pyinstaller.org</a>) which says:</p> <blockquote> <p>The main goal of PyInstaller is to be compatible with 3rd-party packages out-of-the-box. This means that, with PyInstaller, all the required tricks to make external packages work are already integrated within PyInstaller itself so that there is no user intervention required. You'll never be required to look for tricks in wikis and apply custom modification to your files or your setup scripts. Check our compatibility list of SupportedPackages. </p> </blockquote>
1
2009-06-05T13:49:24Z
[ "python", "plugins", "py2exe", "pyinstaller" ]
function pointers in python
307,494
<p>I would like to do something like the following:</p> <pre><code>def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) </code></pre> <p>In python, is it possible to assign something like a function pointer?</p>
2
2008-11-21T01:09:28Z
307,538
<p>Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.</p>
16
2008-11-21T01:30:33Z
[ "python", "function-pointers" ]
function pointers in python
307,494
<p>I would like to do something like the following:</p> <pre><code>def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) </code></pre> <p>In python, is it possible to assign something like a function pointer?</p>
2
2008-11-21T01:09:28Z
307,622
<p>Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value.</p> <p>You can use this to implement a Strategy pattern, for example:</p> <pre><code>def the_simple_way(a, b): # blah blah def the_complicated_way(a, b): # blah blah def foo(way): if way == 'complicated': doit = the_complicated_way else: doit = the_simple_way doit(a, b) </code></pre> <p>Or a lookup table:</p> <pre><code>def do_add(a, b): return a+b def do_sub(a, b): return a-b handlers = { 'add': do_add, 'sub': do_sub, } print handlers[op](a, b) </code></pre> <p>You can even grab a method bound to an object:</p> <pre><code>o = MyObject() f = o.method f(1, 2) # same as o.method(1, 2) </code></pre>
4
2008-11-21T02:14:12Z
[ "python", "function-pointers" ]
function pointers in python
307,494
<p>I would like to do something like the following:</p> <pre><code>def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) </code></pre> <p>In python, is it possible to assign something like a function pointer?</p>
2
2008-11-21T01:09:28Z
700,118
<p>Just a quick note that most Python operators already have an equivalent function in the <a href="http://docs.python.org/library/operator.html" rel="nofollow">operator</a> module.</p>
1
2009-03-31T05:23:18Z
[ "python", "function-pointers" ]
Why do new instances of a class share members with other instances?
307,729
<pre><code>class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() </code></pre> <p>I would expect a return of :</p> <pre><code>2 2 2 </code></pre> <p>But I get :</p> <pre><code>2 4 6 </code></pre> <p>Why is this? I've found that by doing a=[] in the <strong>init</strong>, I can route around this behavior, but I'm less than clear why.</p>
2
2008-11-21T03:22:53Z
307,741
<p><em>doh</em></p> <p>I just figured out why.</p> <p>In the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the <strong>init</strong> block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seems like the class attributes act like static attributes of the class, they're shared by all instances. </p> <p>Whoa. </p> <p>One question though : CodeCompletion sucks like this. In the foo class, I can't do self.(variable), because it's not being defined automatically - it's being defined by a function. Can I define a class variable and replace it with a data variable?</p>
4
2008-11-21T03:27:46Z
[ "python", "scope", "mutable" ]
Why do new instances of a class share members with other instances?
307,729
<pre><code>class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() </code></pre> <p>I would expect a return of :</p> <pre><code>2 2 2 </code></pre> <p>But I get :</p> <pre><code>2 4 6 </code></pre> <p>Why is this? I've found that by doing a=[] in the <strong>init</strong>, I can route around this behavior, but I'm less than clear why.</p>
2
2008-11-21T03:22:53Z
307,775
<p>What you probably want to do is:</p> <pre><code>class Ball: def __init__(self): self.a = [] </code></pre> <p>If you use just <code>a = []</code>, it creates a local variable in the <code>__init__</code> function, which disappears when the function returns. Assigning to <code>self.a</code> makes it an instance variable which is what you're after.</p> <p>For a semi-related gotcha, see how you can <a href="http://stackoverflow.com/questions/146329/what-is-the-worst-gotcha-youve-experienced#147877">change the value of default parameters for future callers</a>.</p>
2
2008-11-21T03:47:25Z
[ "python", "scope", "mutable" ]
Why do new instances of a class share members with other instances?
307,729
<pre><code>class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() </code></pre> <p>I would expect a return of :</p> <pre><code>2 2 2 </code></pre> <p>But I get :</p> <pre><code>2 4 6 </code></pre> <p>Why is this? I've found that by doing a=[] in the <strong>init</strong>, I can route around this behavior, but I'm less than clear why.</p>
2
2008-11-21T03:22:53Z
308,464
<p>"Can I define a class variable and replace it with a data variable?"</p> <p>No. They're separate things. A class variable exists precisely once -- in the class.</p> <p>You could -- to finesse code completion -- start with some class variables and then delete those lines of code after you've written your class. But every time you forget to do that nothing good will happen.</p> <p>Better is to try a different IDE. <a href="http://www.activestate.com/store/download.aspx?prdGUID=20f4ed15-6684-4118-a78b-d37ff4058c5f" rel="nofollow">Komodo Edit</a>'s code completions seem to be sensible.</p> <p>If you have so many variables with such long names that code completion is actually helpful, perhaps you should make your classes smaller or use shorter names. Seriously. </p> <p>I find that when you get to a place where code completion is more helpful than annoying, you've exceeded the "keep it all in my brain" complexity threshold. If the class won't fit in my brain, it's too complex.</p>
1
2008-11-21T11:20:14Z
[ "python", "scope", "mutable" ]
help me translate Java code making use of bytes into jython code
308,187
<p>how do I translate this code into jython?</p> <pre><code> ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file + ".zip")); byte[] buf = new byte[1024]; int len; //Create a new Zip entry with the file's name. ZipEntry zipEntry = new ZipEntry(file.toString()); //Create a buffered input stream out of the file //we're trying to add into the Zip archive. FileInputStream fin = new FileInputStream(file); BufferedInputStream in = new BufferedInputStream(fin); zos.putNextEntry(zipEntry); //Read bytes from the file and write into the Zip archive. while ((len = in.read(buf)) &gt;= 0) { zos.write(buf, 0, len); } //Close the input stream. in.close(); //Close this entry in the Zip stream. zos.closeEntry(); </code></pre> <p>this is what I have but it Fails badly</p> <pre><code> buf=None &lt;&lt;&lt;&lt; ? len=None &lt;&lt;&lt;&lt; ? zipEntry=ZipEntry(file.toString()) fin=FileInputStream(file) bin=BufferedInputStream(fin) self._zos.putNextEntry(zipEntry) while (len=bin.helpme_im_dying(buf)) &gt;= 0): &lt;&lt;&lt;&lt; ? self._zos.write(buf,0,len) &lt;&lt;&lt;&lt; ? len = bin.read(buf) &lt;&lt;&lt;&lt; ? bin.close() self._zos.closeEntry() </code></pre> <p>refer to this page for information <a href="https://www.acm.org/crossroads/xrds6-3/ovp63.html" rel="nofollow">https://www.acm.org/crossroads/xrds6-3/ovp63.html</a></p>
2
2008-11-21T08:30:51Z
308,210
<p>Here's an exact translation of that function (except, like your case, using <code>bin</code> instead of reserved keyword <code>in</code>).</p> <pre><code>from jarray import zeros from java.io import BufferedInputStream, FileInputStream, FileOutputStream from java.util.zip import ZipEntry, ZipOutputStream def test(file): zos = ZipOutputStream(FileOutputStream(file + ".zip")) buf = zeros(1024, 'b') zipEntry = ZipEntry(file) fin = FileInputStream(file) bin = BufferedInputStream(fin) zos.putNextEntry(zipEntry) len = bin.read(buf) while len &gt;= 0: zos.write(buf, 0, len) len = bin.read(buf) bin.close() zos.closeEntry() </code></pre>
4
2008-11-21T08:46:24Z
[ "java", "python", "jython" ]
help me translate Java code making use of bytes into jython code
308,187
<p>how do I translate this code into jython?</p> <pre><code> ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file + ".zip")); byte[] buf = new byte[1024]; int len; //Create a new Zip entry with the file's name. ZipEntry zipEntry = new ZipEntry(file.toString()); //Create a buffered input stream out of the file //we're trying to add into the Zip archive. FileInputStream fin = new FileInputStream(file); BufferedInputStream in = new BufferedInputStream(fin); zos.putNextEntry(zipEntry); //Read bytes from the file and write into the Zip archive. while ((len = in.read(buf)) &gt;= 0) { zos.write(buf, 0, len); } //Close the input stream. in.close(); //Close this entry in the Zip stream. zos.closeEntry(); </code></pre> <p>this is what I have but it Fails badly</p> <pre><code> buf=None &lt;&lt;&lt;&lt; ? len=None &lt;&lt;&lt;&lt; ? zipEntry=ZipEntry(file.toString()) fin=FileInputStream(file) bin=BufferedInputStream(fin) self._zos.putNextEntry(zipEntry) while (len=bin.helpme_im_dying(buf)) &gt;= 0): &lt;&lt;&lt;&lt; ? self._zos.write(buf,0,len) &lt;&lt;&lt;&lt; ? len = bin.read(buf) &lt;&lt;&lt;&lt; ? bin.close() self._zos.closeEntry() </code></pre> <p>refer to this page for information <a href="https://www.acm.org/crossroads/xrds6-3/ovp63.html" rel="nofollow">https://www.acm.org/crossroads/xrds6-3/ovp63.html</a></p>
2
2008-11-21T08:30:51Z
308,462
<p>It is not an answer to your question, but related. Here is a CPython version:</p> <pre><code>from zipfile import ZipFile, ZIP_DEFLATED def test(file): ZipFile(file+".zip", "w", ZIP_DEFLATED).write(file) </code></pre>
1
2008-11-21T11:19:31Z
[ "java", "python", "jython" ]
help me translate Java code making use of bytes into jython code
308,187
<p>how do I translate this code into jython?</p> <pre><code> ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file + ".zip")); byte[] buf = new byte[1024]; int len; //Create a new Zip entry with the file's name. ZipEntry zipEntry = new ZipEntry(file.toString()); //Create a buffered input stream out of the file //we're trying to add into the Zip archive. FileInputStream fin = new FileInputStream(file); BufferedInputStream in = new BufferedInputStream(fin); zos.putNextEntry(zipEntry); //Read bytes from the file and write into the Zip archive. while ((len = in.read(buf)) &gt;= 0) { zos.write(buf, 0, len); } //Close the input stream. in.close(); //Close this entry in the Zip stream. zos.closeEntry(); </code></pre> <p>this is what I have but it Fails badly</p> <pre><code> buf=None &lt;&lt;&lt;&lt; ? len=None &lt;&lt;&lt;&lt; ? zipEntry=ZipEntry(file.toString()) fin=FileInputStream(file) bin=BufferedInputStream(fin) self._zos.putNextEntry(zipEntry) while (len=bin.helpme_im_dying(buf)) &gt;= 0): &lt;&lt;&lt;&lt; ? self._zos.write(buf,0,len) &lt;&lt;&lt;&lt; ? len = bin.read(buf) &lt;&lt;&lt;&lt; ? bin.close() self._zos.closeEntry() </code></pre> <p>refer to this page for information <a href="https://www.acm.org/crossroads/xrds6-3/ovp63.html" rel="nofollow">https://www.acm.org/crossroads/xrds6-3/ovp63.html</a></p>
2
2008-11-21T08:30:51Z
25,662,884
<p>Don't use ZipFile without ensuring it is closed:</p> <pre><code>with ZipFile('spam.zip', 'w') as myzip: myzip.write('eggs.txt') </code></pre>
0
2014-09-04T10:16:30Z
[ "java", "python", "jython" ]
Showing processing message in Python
308,220
<p>I want to show the processing information or log in the original page when the submitted request is being served until it completes the execution. I thought it would be meaningful to the user to know what is happening behind the request.</p> <p>I don't find a clue to do so though, can you guys help me out as how people are doing like this one below one - for your reference</p> <p><a href="http://www.xml-sitemaps.com/" rel="nofollow">http://www.xml-sitemaps.com/</a></p>
0
2008-11-21T08:50:27Z
308,237
<p>there are two ways i could imagine handling this:</p> <ol> <li><p>have your backend script (python) output the information of a long process to a log of some sort (text file, database, session, etc...) and then have javascript grab the information via ajax and update the current page.</p></li> <li><p>same deal, but instead of ajax just have a meta refresh on the page which would grab the latest updated information.</p></li> </ol>
1
2008-11-21T09:07:17Z
[ "python" ]
Showing processing message in Python
308,220
<p>I want to show the processing information or log in the original page when the submitted request is being served until it completes the execution. I thought it would be meaningful to the user to know what is happening behind the request.</p> <p>I don't find a clue to do so though, can you guys help me out as how people are doing like this one below one - for your reference</p> <p><a href="http://www.xml-sitemaps.com/" rel="nofollow">http://www.xml-sitemaps.com/</a></p>
0
2008-11-21T08:50:27Z
1,865,400
<p>you may use python threading, which will create a new process in background</p> <p>and display your messages on that thread</p> <p>hope it helps ;)</p>
0
2009-12-08T08:00:28Z
[ "python" ]
How to force iPython to use an older version of Python?
308,254
<p>I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.</p> <p>Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.</p> <p>Before, there was a ipython2.4 package but it is deprecated.</p>
9
2008-11-21T09:26:19Z
308,260
<p>Ok, I answer my own question : I'm dumb :-)</p> <pre><code>ls /usr/bin/ipython* /usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5 </code></pre> <p>Now it's built-in...</p>
10
2008-11-21T09:28:51Z
[ "python", "ipython" ]
How to force iPython to use an older version of Python?
308,254
<p>I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.</p> <p>Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.</p> <p>Before, there was a ipython2.4 package but it is deprecated.</p>
9
2008-11-21T09:26:19Z
5,293,422
<p>I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with <a href="https://launchpad.net/~fkrull/+archive/deadsnakes" rel="nofollow">the deadsnakes ppa</a>.)</p> <p>To get ipython2.5, I installed ipython from your virtualenv:</p> <pre><code>virtualenv --python=/usr/bin/python2.5 project_name source project_name/bin/activate pip install ipython </code></pre> <p>Then the ipython version should match the python passed into virtualenv with <code>--python</code>.</p>
4
2011-03-14T00:07:02Z
[ "python", "ipython" ]
How to force iPython to use an older version of Python?
308,254
<p>I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.</p> <p>Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.</p> <p>Before, there was a ipython2.4 package but it is deprecated.</p>
9
2008-11-21T09:26:19Z
18,981,744
<p>You can just:</p> <pre><code>$ python2.4 setup.py install --prefix=$HOME/usr $ python2.5 setup.py install --prefix=$HOME/usr </code></pre> <p>or </p> <pre><code>alias ip4 "python2.4 $HOME/usr/bin/ipython" alias ip5 "python2.5 $HOME/usr/bin/ipython" </code></pre> <p><a href="https://github.com/ipython/ipython/wiki/Frequently-asked-questions#q-running-ipython-against-multiple-versions-of-python" rel="nofollow">fyi</a></p>
0
2013-09-24T12:33:19Z
[ "python", "ipython" ]
Python data structures overhead/performance
308,912
<p>Is there any performance advantage to using lists over dictionaries over tuples in Python?</p> <p>If I'm optimising for speed, is there any reason to prefer one over another?</p>
3
2008-11-21T14:22:56Z
308,936
<p>Tuples will be slightly faster to construct for a small number of elements. Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists.</p> <p>With that being said, the performance difference should be negligible, and in general you shouldn't worry about these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck.</p>
6
2008-11-21T14:31:28Z
[ "python", "optimization" ]
Python data structures overhead/performance
308,912
<p>Is there any performance advantage to using lists over dictionaries over tuples in Python?</p> <p>If I'm optimising for speed, is there any reason to prefer one over another?</p>
3
2008-11-21T14:22:56Z
308,964
<p>The big difference is that tuples are immutable, while lists and dictionaries are mutable data structures. This means that tuples are also faster, so if you have a collection of items that doesn't change, you should prefer them over lists.</p>
2
2008-11-21T14:40:36Z
[ "python", "optimization" ]
Python data structures overhead/performance
308,912
<p>Is there any performance advantage to using lists over dictionaries over tuples in Python?</p> <p>If I'm optimising for speed, is there any reason to prefer one over another?</p>
3
2008-11-21T14:22:56Z
308,982
<p>Rich,</p> <p>Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.</p> <p>That may sound obvious, but picking the correct data structures algorithmically has much higher performance gains that micro-optimization due to more efficient compiled code layouts, etc. If you search in a list in O(n) instead of in a dict in O(1), micro-optimizations won't save you.</p>
19
2008-11-21T14:47:13Z
[ "python", "optimization" ]
Python data structures overhead/performance
308,912
<p>Is there any performance advantage to using lists over dictionaries over tuples in Python?</p> <p>If I'm optimising for speed, is there any reason to prefer one over another?</p>
3
2008-11-21T14:22:56Z
310,334
<p>See the following.</p> <ul> <li><a href="http://stackoverflow.com/questions/172720/speeding-up-python">Speeding Up Python</a></li> <li><a href="http://stackoverflow.com/questions/178045/when-should-you-start-optimising-code">When should you start optimising code</a></li> <li><a href="http://stackoverflow.com/questions/211414/is-premature-optimization-really-the-root-of-all-evil">Is premature optimization really the root of all evil?</a></li> <li><a href="http://stackoverflow.com/questions/68630/are-tuples-more-efficient-than-lists-in-python">Are tuples more efficient than lists in Python?</a></li> </ul>
0
2008-11-21T21:52:54Z
[ "python", "optimization" ]
pygtk glade question: why isn't this simple script working?
308,913
<p>I've been writing writing a small pygtk application using glade to put together the UIs. I've created several windows already that work, but for some reason this one isn't working. I get the following traceback:</p> <pre><code>Traceback (most recent call last): File "test.py", line 7, in &lt;module&gt; class TestClass: File "test.py", line 10, in TestClass self.wTree.signal_autoconnect(self) NameError: name 'self' is not defined </code></pre> <p>Here is the contents of test.py:</p> <pre><code>#!/usr/bin/env python import pygtk import gtk import gtk.glade class TestClass: def __init__(self): self.wTree = gtk.glade.XML("test.glade") self.wTree.signal_autoconnect(self) def on_TestClass_destroy(self, widget, data): gtk.main_quit() if __name__ == "__main__": window = TestClass() gtk.main() </code></pre> <p>And here is the glade file, test.glade:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"&gt; &lt;!--Generated with glade3 3.4.5 on Fri Nov 21 08:53:53 2008 --&gt; &lt;glade-interface&gt; &lt;widget class="GtkWindow" id="TestWindow"&gt; &lt;property name="visible"&gt;True&lt;/property&gt; &lt;property name="title" translatable="yes"&gt;Test Window&lt;/property&gt; &lt;signal name="destroy" handler="on_TestClass_destroy"/&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;/widget&gt; &lt;/glade-interface&gt; </code></pre> <p>The strange thing is that if I take out the signal_autoconnect(self) call, the window opens. But if I replace that call with "self.on_TestClass_destroy(self, None, None)" instead, it returns the same NameError exception.</p> <p>I really don't understand why this isn't working, as I've created several other window classes that work fine.</p> <p>Is the following code working for anyone here?</p>
1
2008-11-21T14:22:56Z
308,984
<p>That code and window and signal connection work fine here.</p> <p>There is a small bug though when calling the signal handler. The signal handler should not have a data argument, since only the widget is passed as an argument.</p> <pre><code>def on_TestClass_destroy(self, widget): gtk.main_quit() </code></pre> <p>The data argument(s) are only those provided on connect in case you need extra state for a signal handler.</p>
4
2008-11-21T14:49:35Z
[ "python", "gtk", "pygtk", "glade" ]
What does functools.wraps do?
308,999
<p>In a comment on the <a href="http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277">answer to another question</a>, someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?</p>
265
2008-11-21T14:53:40Z
309,000
<p>When you use a decorator, you're replacing one function with another. In other words, if you have a decorator</p> <pre><code>def logged(func): def with_logging(*args, **kwargs): print func.__name__ + " was called" return func(*args, **kwargs) return with_logging </code></pre> <p>then when you say</p> <pre><code>@logged def f(x): """does some math""" return x + x * x </code></pre> <p>it's exactly the same as saying</p> <pre><code>def f(x): """does some math""" return x + x * x f = logged(f) </code></pre> <p>and your function f is replaced with the function with_logging. Unfortunately, this means that if you then say</p> <pre><code>print f.__name__ </code></pre> <p>it will print <code>with_logging</code> because that's the name of your new function. In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument <code>x</code>; instead it'll be listed as taking <code>*args</code> and <code>**kwargs</code> because that's what with_logging takes.</p> <p>If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have <code>functools.wraps</code>. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since <code>wraps</code> is itself a decorator, the following code does the correct thing:</p> <pre><code>from functools import wraps def logged(func): @wraps(func) def with_logging(*args, **kwargs): print func.__name__ + " was called" return func(*args, **kwargs) return with_logging @logged def f(x): """does some math""" return x + x * x print f.__name__ # prints 'f' print f.__doc__ # prints 'does some math' </code></pre>
467
2008-11-21T14:53:47Z
[ "python", "decorator", "wraps" ]
What does functools.wraps do?
308,999
<p>In a comment on the <a href="http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277">answer to another question</a>, someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?</p>
265
2008-11-21T14:53:40Z
1,843,920
<p>I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute <code>__name__</code>. I had a specific issue with this that was pretty hard to trace where Django was reporting the error "object has no attribute '<code>__name__</code>'". Unfortunately, for class-style decorators, I don't believe that @wrap will do the job. I have instead created a base decorator class like so:</p> <pre><code>class DecBase(object): func = None def __init__(self, func): self.__func = func def __getattribute__(self, name): if name == "func": return super(DecBase, self).__getattribute__(name) return self.func.__getattribute__(name) def __setattr__(self, name, value): if name == "func": return super(DecBase, self).__setattr__(name, value) return self.func.__setattr__(name, value) </code></pre> <p>This class proxies all the attribute calls over to the function that is being decorated. So, you can now create a simple decorator that checks that 2 arguments are specified like so:</p> <pre><code>class process_login(DecBase): def __call__(self, *args): if len(args) != 2: raise Exception("You can only specify two arguments") return self.func(*args) </code></pre>
11
2009-12-03T23:46:43Z
[ "python", "decorator", "wraps" ]
Why can't I inherit from dict AND Exception in Python?
309,129
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
18
2008-11-21T15:37:42Z
309,196
<p>What version of Python?</p> <p>In 2.5.1, I can't even define a class the inherits from both <code>dict</code> and <code>Exception</code>:</p> <pre><code>&gt;&gt;&gt; class foo(dict, Exception): ... 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>If you're using an older version, maybe it doesn't do this check during type definition and the conflict causes oddities later on.</p>
3
2008-11-21T15:55:23Z
[ "python", "multiple-inheritance" ]
Why can't I inherit from dict AND Exception in Python?
309,129
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
18
2008-11-21T15:37:42Z
309,211
<h2>No reason but a solution</h2> <p>For the moment I still don't know the why, but I bypass it using <code>UserDict.UserDict</code>. It's slower since it's pure Python, but I don't think on this part of the app it will be troublesome.</p> <p>Still interested about the answer anyway ;-)</p>
3
2008-11-21T16:00:08Z
[ "python", "multiple-inheritance" ]
Why can't I inherit from dict AND Exception in Python?
309,129
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
18
2008-11-21T15:37:42Z
309,563
<p>Both <code>Exception</code> and <code>dict</code> are implemented in C.</p> <p>I think you can test this the follwing way:</p> <pre><code>&gt;&gt;&gt; class C(object): pass ... &gt;&gt;&gt; '__module__' in C.__dict__ True &gt;&gt;&gt; '__module__' in dict.__dict__ False &gt;&gt;&gt; '__module__' in Exception.__dict__ False </code></pre> <p>Since <code>Exception</code> and <code>dict</code> have different ideas of how to store their data internally, they are not compatible and thus you cannot inherit from both at the same time.</p> <p>In later versions of Python you should get an Exception the moment you try to define the class:</p> <pre><code>&gt;&gt;&gt; class foo(dict, Exception): ... 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>
20
2008-11-21T17:30:50Z
[ "python", "multiple-inheritance" ]
Why can't I inherit from dict AND Exception in Python?
309,129
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
18
2008-11-21T15:37:42Z
310,273
<p>What's wrong with this?</p> <pre><code>class ConstraintFailure( Exception ): def __init__( self, **failures ): self.failures= failures # already a dict, don't need to do anything def __getitem__( self, key ): return self.failures.get(key) </code></pre> <p>This is an Exception, and it contains other exceptions in an internal dictionary named <code>failures</code>.</p> <p>Could you update your problem to list some some specific thing this can't do?</p> <pre><code>try: raise ConstraintFailure( x=ValueError, y=Exception ) except ConstraintFailure, e: print e['x'] print e['y'] &lt;type 'exceptions.ValueError'&gt; &lt;type 'exceptions.Exception'&gt; </code></pre>
4
2008-11-21T21:35:39Z
[ "python", "multiple-inheritance" ]
Why can't I inherit from dict AND Exception in Python?
309,129
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
18
2008-11-21T15:37:42Z
924,952
<p>I am almost certain that with 2.4 problem is caused by exceptions being old style classes.</p> <pre><code>$ python2.4 Python 2.4.4 (#1, Feb 19 2009, 09:13:34) &gt;&gt;&gt; type(dict) &lt;type 'type'&gt; &gt;&gt;&gt; type(Exception) &lt;type 'classobj'&gt; &gt;&gt;&gt; type(Exception()) &lt;type 'instance'&gt; $ python2.5 Python 2.5.4 (r254:67916, Feb 17 2009, 23:11:16) &gt;&gt;&gt; type(Exception) &lt;type 'type'&gt; &gt;&gt;&gt; type(Exception()) &lt;type 'exceptions.Exception'&gt; </code></pre> <p>In both versions as the message says exceptions can be classes, instances (of old style classes) or strings (deprecated).</p> <p>From version 2.5 exception hierarchy is based on new style classes finally. And instances of new style classes which inherit from BaseException are now allowed too. But in 2.4 multiple inheritance from Exception (old style class) and dict (new style class) results in new style class which is not allowed as exception (mixing old and new style classes is probably bad anyway).</p>
0
2009-05-29T08:22:38Z
[ "python", "multiple-inheritance" ]
Why can't I inherit from dict AND Exception in Python?
309,129
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
18
2008-11-21T15:37:42Z
34,334,644
<p>Use <code>collections.UserDict</code> to avoid metaclass conflicts:</p> <pre><code>class ConstraintFailureSet(coll.UserDict, Exception): """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : coll.UserDict.__init__(self, failures) Exception.__init__(self) print( isinstance(ConstraintFailureSet(), Exception)) #True raise ConstraintFailureSet() </code></pre>
0
2015-12-17T12:30:02Z
[ "python", "multiple-inheritance" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
309,783
<p>First Option - Online Installation (i.e. remaining connected to the Internet during the entire installation process):</p> <ol> <li>Download <a href="http://pypi.python.org/pypi/setuptools#files">setuptools-0.6c9.tar.gz</a></li> <li>Use <a href="http://www.7-zip.org/">7-zip</a> to extract it to a folder(directory) outside your Windows Python installation folder</li> <li>Go the folder (refer step 2) and run ez_setup.py from the corresponding dos (command) prompt</li> <li>Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory</li> </ol> <p>Second Option:</p> <ol> <li>Download <a href="http://pypi.python.org/pypi/setuptools#files">setuptools-0.6c9.tar.gz</a></li> <li>Download <a href="http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c9-py2.6.egg#md5=ca37b1ff16fa2ede6e19383e7b59245a">setuptools-0.6c9-py2.6.egg</a> to a folder(directory) outside your Windows Python installation folder</li> <li>Use <a href="http://www.7-zip.org/">7-zip</a> to extract ez_setup.py in the same folder as <a href="http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c9-py2.6.egg#md5=ca37b1ff16fa2ede6e19383e7b59245a">setuptools-0.6c9-py2.6.egg</a></li> <li>Go to the corresponding dos prompt and run python ez_setup.py setuptools-0.6c9-py2.6.egg from the command prompt</li> <li>Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory</li> </ol> <p>Third Option (assuming that you have Visual Studio 2005 or MinGW on your machine)</p> <ol> <li>Download <a href="http://pypi.python.org/pypi/setuptools#files">setuptools-0.6c9.tar.gz</a></li> <li>Use <a href="http://www.7-zip.org/">7-zip</a> to extract it to a folder(directory) outside your Windows Python installation folder</li> <li>Go the folder (refer step 2) and run python setup.py install from the corresponding dos (command) prompt</li> </ol> <p>Please provide feedback.</p>
102
2008-11-21T18:56:40Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
380,007
<p>I got it working quickly by downloading the source and then running (from the extracted directory):</p> <pre><code>python.exe setup.py bdist_wininst </code></pre> <p>That builds <code>dist\setuptools-0.6c9.win32.exe</code>, which is exactly the installer you're looking for.</p>
5
2008-12-19T03:15:06Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
425,318
<p>You could download and run <a href="http://peak.telecommunity.com/dist/ez_setup.py" rel="nofollow">http://peak.telecommunity.com/dist/ez_setup.py</a>. This will download and install setuptools.</p> <p>[update]</p> <p>This script no longer works - the version of setuptools the it downloads is not at the URI specified in ez_setup.py -navigate to <a href="http://pypi.python.org/packages/2.7/s/setuptools/" rel="nofollow">http://pypi.python.org/packages/2.7/s/setuptools/</a> for the latest version - the script also does some md5 checking, I haven't looked into it any further.</p>
50
2009-01-08T18:27:59Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
675,337
<p>The Nov. 21 answer didn't work for me. I got it working on my 64 bit Vista machine by following the Method 1 instructions, except for Step 3 I typed:</p> <p>setup.py install</p> <p>So, in summary, I did:</p> <ol> <li>Download setuptools-0.6c9.tar.gz</li> <li>Use 7-zip to extract it to a folder (directory) outside your Windows Python installation folder</li> <li>At a DOS (command) prompt, cd to your the newly created setuptools-0.6c9 folder and type "setup.py install" (without the quotes).</li> <li>Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory</li> </ol>
10
2009-03-23T21:37:23Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
675,373
<p>My advice is to wait until Python 2.6.2 to use Python 2.6 on Windows. There are still some bugs that make it less than ideal (<a href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=2609380&amp;group%5Fid=78018&amp;atid=551954" rel="nofollow">this one is particularly nasty</a>). Personally, I wasn't able to get setuptools working totally well on Vista x64 even after installing from source. Under Python 2.5.4, I haven't had any problems though.</p>
0
2009-03-23T21:49:22Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
706,069
<p>The "first option" (4 steps: download, extract, run, verify PATH) didn't work on my Windows Server 2008 x64 machine with Python 2.6 32 bit installed, nor did it work on my Vista x64 machine with Python 2.6 32 bit installed.</p> <p>The "second option (5 steps: download, extract, extract, run, verify PATH) worked on both Windows Server 2008 x64 and on Windows Vista x64.</p> <p>Thanks a bunch for providing the instructions!</p>
1
2009-04-01T15:32:06Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
759,009
<p>Just installed setuptools as follows:</p> <ol> <li>Downloaded <a href="http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c9.tar.gz#md5=3864c01d9c719c8924c455714492295e" rel="nofollow">http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c9.tar.gz#md5=3864c01d9c719c8924c455714492295e</a> , and extracted to a folder outside of my Python installation.</li> <li>command prompt, then cd into that folder.</li> <li>enter <em>python setup.py install</em></li> </ol> <p>That will install from the source into your python's site-packages folder and any other steps needed. This was on Windows XP SP2.</p>
2
2009-04-17T04:21:19Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
817,335
<p>Second option worked for me.</p> <p>Two notes:</p> <p>a. After installing, when you using easy_install in vista, do so as administrator. (Right click on your command line shortcut and click "run as administrator"). I had trouble trying to run easy_install without doing that.</p> <p>b. He means use ez_setup from setuptools-0.6c9.tar.gz</p>
0
2009-05-03T15:39:56Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
897,332
<p>OP option 1 did not work for me.</p> <p>However doing setup.py install as mentioned by NathanD did do the trick.</p> <p>Maybe that should become option 1?</p> <p>Werner</p>
1
2009-05-22T10:59:37Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
1,740,321
<p>I'm able to find the EXE doing google,</p> <p>you can simply download it from following URL, and double click and install....</p> <p><a href="http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11.win32-py2.6.exe#md5=1509752c3c2e64b5d0f9589aafe053dc" rel="nofollow">http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11.win32-py2.6.exe#md5=1509752c3c2e64b5d0f9589aafe053dc</a></p>
6
2009-11-16T05:56:23Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
1,936,825
<p><a href="http://activestate.com/activepython" rel="nofollow">ActivePython</a> already includes setuptools (<a href="http://python-distribute.org/" rel="nofollow">Distribute</a> actually), along with pip and virtualenv. </p>
-1
2009-12-20T20:00:59Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
2,755,659
<p><code>setuptools</code> <a href="http://pypi.python.org/pypi/setuptools/0.6c11" rel="nofollow">has been updated</a> in version 0.6c11.</p>
1
2010-05-03T00:52:29Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
6,418,818
<p>The easiest setuptools installation option is to use the pre-packaged Windows Installer.</p> <p>for <strong>32-bit</strong> Python on Windows, the official setuptools page has been updated and has windows installers for Python 2.6 and 2.7:</p> <ul> <li><a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">http://pypi.python.org/pypi/setuptools</a></li> </ul> <p>for <strong>64-bit</strong> Python on Windows, setuptools Windows installers are available here:</p> <ul> <li><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></li> </ul>
1
2011-06-20T23:45:52Z
[ "python", "windows", "setuptools" ]
How to setup setuptools for python 2.6 on Windows?
309,412
<p>Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? </p> <p>There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. </p> <p>Does anyone know of a way to install it anyway?</p>
84
2008-11-21T16:44:44Z
22,721,532
<p>Python has everything on board to do this.</p> <p>from <a href="https://pypi.python.org/pypi/setuptools#installing-and-using-setuptools" rel="nofollow">https://pypi.python.org/pypi/setuptools#installing-and-using-setuptools</a> I got the URL to the <strong>ez_setup.py</strong>: <a href="https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py" rel="nofollow">https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py</a></p> <p>instead downloading it and fiddling with the file we can do this from the console:</p> <pre><code>import urllib url = 'https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py' ezcode = urllib.urlopen(url).read() exec(ezcode) </code></pre>
0
2014-03-28T19:26:30Z
[ "python", "windows", "setuptools" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
310,011
<p>This is going to be DB dependent. In the case of MySQLdb, for example, the <code>connection</code> class has a <code>literal</code> method that will convert the value to the correct escaped representation for passing to MySQL (that's what <code>cursor.execute</code> uses).</p> <p>I imagine Postgres has something similar, but I don't think there is a function to escape values as part of the DB API 2.0 spec.</p>
0
2008-11-21T20:07:31Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
310,078
<p>This'll be database dependent (iirc, mysql allows <code>\</code> as an escape character, while something like oracle expects quotes to be doubled: <code>'my '' quoted string'</code>).</p> <p>Someone correct me if i'm wrong, but the double-quoting method is the standard method.</p> <p>It may be worth looking at what other db abstraction libraries do (sqlalchemy, cx_Oracle, sqlite, etc).</p> <p>I've got to ask - why do you want to inline the values instead of bind them?</p>
0
2008-11-21T20:25:48Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
310,591
<p>You should try to avoid doing your own quoting. Not only will it be DB-specific as people have pointed out, but flaws in quoting are the source of SQL injection bugs.</p> <p>If you don't want to pass around queries and values separately, then pass around a list of the parameters:</p> <pre><code>def make_my_query(): # ... return sql, (value1, value2) def do_it(): query = make_my_query() cursor.execute(*query) </code></pre> <p>(I probably have the syntax of cursor.execute wrong) The point here is that just because cursor.execute takes a number of arguments, that doesn't mean you have to handle them all separately. You can deal with them as one list.</p>
2
2008-11-22T00:01:40Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
312,423
<p>Ok, so I was curious and went and looked at the source of psycopg2. Turns out I didn't have to go further than the examples folder :)</p> <p>And yes, this is psycopg2-specific. Basically, if you just want to quote a string you'd do this:</p> <pre><code>from psycopg2.extensions import adapt print adapt("Hello World'; DROP DATABASE World;") </code></pre> <p>But what you probably want to do is to write and register your own adapter;</p> <p>In the examples folder of psycopg2 you find the file <a href="http://sourcecodebrowser.com/psycopg2/2.4.5/myfirstrecipe_8py_source.html">'myfirstrecipe.py'</a> there is an example of how to cast and quote a specific type in a special way.</p> <p>If you have objects for the stuff you want to do, you can just create an adapter that conforms to the 'IPsycopgSQLQuote' protocol (see pydocs for the myfirstrecipe.py-example...actually that's the only reference I can find to that name) that quotes your object and then registering it like so:</p> <pre><code>from psycopg2.extensions import register_adapter register_adapter(mytype, myadapter) </code></pre> <p>Also, the other examples are interesting; esp. <a href="http://sourcecodebrowser.com/psycopg2/2.4.5/dialtone_8py_source.html">'dialtone.py'</a> and <a href="http://sourcecodebrowser.com/psycopg2/2.4.5/simple_8py_source.html">'simple.py'</a>.</p>
22
2008-11-23T11:47:54Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
312,577
<p>If you use django you might want to use the quoting function which is automatically adapted to the currently configured DBMS :</p> <pre><code>from django.db import backend my_quoted_variable = backend.DatabaseOperations().quote_name(myvar) </code></pre>
-1
2008-11-23T14:39:48Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
312,607
<p>I don't think you give any sufficient reasoning behind your avoidance to do this The Right Way. Please, use the APi as it is designed and don't try so hard to make your code less readable for the next guy and more fragile.</p>
1
2008-11-23T15:17:20Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
13,848,683
<p>Your code snippet would get just like this, according to <a href="http://initd.org/psycopg/docs/extensions.html" rel="nofollow">psycopg extension docs</a></p> <pre><code>from psycopg2.extensions import adapt value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ adapt(value).getquoted() cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>The <code>getquoted</code> function returns the <code>value</code> as a quoted and escaped string, so you could also go: <code>"SELECT * FROM some_table WHERE some_char_field = " + adapt(value).getquoted()</code> .</p>
0
2012-12-12T21:09:27Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
14,763,136
<pre><code>import re def db_quote(s): return "\"" + re.escape(s) + "\"" </code></pre> <p>can do the job of simple quoting that works at least with MySQL. What we really need, though is cursor.format() function that would work like cursor.execute() except it would return the resulting query instead of executing it. There are times when you do not want the query to be executed quite yet - e.g you may want to log it first, or print it out for debugging before you go ahead with it.</p>
-1
2013-02-07T23:32:41Z
[ "python", "sql", "django", "psycopg2" ]
How to quote a string value explicitly (Python DB API/Psycopg2)
309,945
<p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p> <p>By "implicit quotation" I mean:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted </code></pre> <p>I would prefer something like that:</p> <pre><code>value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too </code></pre> <p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
22
2008-11-21T19:47:11Z
24,590,439
<p>I guess you're looking for the <a href="http://initd.org/psycopg/docs/cursor.html#cursor.mogrify">mogrify</a> function.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')) "INSERT INTO test (num, data) VALUES (42, E'bar')" </code></pre>
10
2014-07-05T20:46:46Z
[ "python", "sql", "django", "psycopg2" ]
Python - Setting / Getting Environment Variables and Addrs
310,118
<p>I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?</p> <p>Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold:</p> <ul> <li><p>Is there a way to get the address in memory of an environment variable?</p></li> <li><p>Can this only be done in bash/C or can I do it purely in Python?</p></li> </ul>
1
2008-11-21T20:37:47Z
310,152
<p>The built in function id() returns a unique id for any object, which just happens to be it's memory address. </p> <p><a href="http://docs.python.org/library/functions.html#id" rel="nofollow">http://docs.python.org/library/functions.html#id</a></p>
1
2008-11-21T20:50:52Z
[ "python", "linux", "environment-variables" ]
Python - Setting / Getting Environment Variables and Addrs
310,118
<p>I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?</p> <p>Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold:</p> <ul> <li><p>Is there a way to get the address in memory of an environment variable?</p></li> <li><p>Can this only be done in bash/C or can I do it purely in Python?</p></li> </ul>
1
2008-11-21T20:37:47Z
310,299
<p>For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable.</p>
4
2008-11-21T21:42:13Z
[ "python", "linux", "environment-variables" ]
Python - Setting / Getting Environment Variables and Addrs
310,118
<p>I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?</p> <p>Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold:</p> <ul> <li><p>Is there a way to get the address in memory of an environment variable?</p></li> <li><p>Can this only be done in bash/C or can I do it purely in Python?</p></li> </ul>
1
2008-11-21T20:37:47Z
310,717
<p>Pass the address itself in an environment variable, and just read it with os.getenv().</p>
0
2008-11-22T01:50:44Z
[ "python", "linux", "environment-variables" ]
How can I translate the following filename to a regular expression in Python?
310,199
<p>I am battling regular expressions now as I type. </p> <p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p> <p><strong><em>Further clarification of question:</em></strong></p> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
2
2008-11-21T21:08:07Z
310,211
<p>To avoid confusion, read the following, in order.</p> <p>First, you have the <a href="http://www.python.org/doc/2.5.2/lib/module-glob.html" rel="nofollow">glob</a> module, which handles file name regular expressions just like the Windows and unix shells.</p> <p>Second, you have the <a href="http://www.python.org/doc/2.5.2/lib/module-fnmatch.html" rel="nofollow">fnmatch</a> module, which just does pattern matching using the unix shell rules.</p> <p>Third, you have the <a href="http://www.python.org/doc/2.5.2/lib/module-re.html" rel="nofollow">re</a> module, which is the complete set of regular expressions.</p> <p>Then ask another, more specific question.</p>
4
2008-11-21T21:14:03Z
[ "python", "regex" ]
How can I translate the following filename to a regular expression in Python?
310,199
<p>I am battling regular expressions now as I type. </p> <p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p> <p><strong><em>Further clarification of question:</em></strong></p> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
2
2008-11-21T21:08:07Z
310,267
<p>Your question is a bit unclear. You say you want a regular expression, but could it be that you want a glob-style pattern you can use with commands like ls? glob expressions and regular expressions are similar in concept but different in practice (regular expressions are considerably more powerful, glob style patterns are easier for the most common cases when looking for files. </p> <p>Also, what do you consider to be the pattern? Certainly, * (glob) or .* (regex) will match the pattern. Also, *<em>test.ext (glob) or .</em>_test.ext (regexp) pattern would match, as would many other variations. </p> <p>Can you be more specific about the pattern? For example, you might describe it as "b, followed by digits, followed by cv, followed by digits ..." </p> <p>Once you can precisely explain the pattern in your native language (and that must be your first step), it's usually a fairly straight-forward task to translate that into a glob or regular expression pattern. </p>
1
2008-11-21T21:33:58Z
[ "python", "regex" ]
How can I translate the following filename to a regular expression in Python?
310,199
<p>I am battling regular expressions now as I type. </p> <p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p> <p><strong><em>Further clarification of question:</em></strong></p> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
2
2008-11-21T21:08:07Z
310,513
<p>if the letters are unimportant, you could try \w\d\d\d\w\w\d\d_test.ext which would match the letter/number pattern, or b\d\d\dcv\d\d_test.ext or some mix of the two.</p>
0
2008-11-21T23:07:05Z
[ "python", "regex" ]
How can I translate the following filename to a regular expression in Python?
310,199
<p>I am battling regular expressions now as I type. </p> <p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p> <p><strong><em>Further clarification of question:</em></strong></p> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
2
2008-11-21T21:08:07Z
310,924
<p>When working with regexes I find the <a href="http://mochikit.com/examples/mochiregexp/index.html" rel="nofollow">Mochikit regex example</a> to be a great help.</p> <pre><code>/^b\d\d\dcv\d\d_test\.ext$/ </code></pre> <p>Then use the python re (regex) module to do the match. This is of course assuming regex is really what you need and not glob as the others mentioned.</p>
0
2008-11-22T05:37:30Z
[ "python", "regex" ]
How can I translate the following filename to a regular expression in Python?
310,199
<p>I am battling regular expressions now as I type. </p> <p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p> <p><strong><em>Further clarification of question:</em></strong></p> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
2
2008-11-21T21:08:07Z
311,033
<blockquote> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p> </blockquote> <pre><code>^b\d{3}cv\d{2}_release\.ext$ </code></pre>
3
2008-11-22T07:47:13Z
[ "python", "regex" ]
How can I translate the following filename to a regular expression in Python?
310,199
<p>I am battling regular expressions now as I type. </p> <p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p> <p><strong><em>Further clarification of question:</em></strong></p> <p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
2
2008-11-21T21:08:07Z
311,214
<p>Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;)</p> <blockquote> <p>must start with</p> </blockquote> <p>The caret (<code>^</code>) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol.</p> <blockquote> <p>'b',</p> </blockquote> <p>Any non-special character in your re will match literally, so you just use "b" for this part: <code>^b</code>.</p> <blockquote> <p>followed by [...] digits,</p> </blockquote> <p>This depends a bit on which flavor of re you use:</p> <p>The most general way of expressing this is to use brackets (<code>[]</code>). Those mean "match any one of the characters listed within. <code>[ASDF]</code> for example would match either <code>A</code> or <code>S</code> or <code>D</code> or <code>F</code>, <code>[0-9]</code> would match anything between 0 and 9.</p> <p>Your re library probably has a shortcut for "any digit". In <code>sed</code> and <code>awk</code> you could use <code>[[:digit:]]</code> [sic!], in python and many other languages you can use <code>\d</code>.</p> <p>So now your re reads <code>^b\d</code>.</p> <blockquote> <p>followed by three [...]</p> </blockquote> <p>The most simple way to express this would be to just repeat the atom three times like this: <code>\d\d\d</code>.</p> <p>Again your language might provide a shortcut: braces (<code>{}</code>). Sometimes you would have to escape them with a backslash (if you are using sed or awk, read about "extended regular expressions"). They also give you a way to say "at least x, but no more than y occurances of the previous atom": <code>{x,y}</code>.</p> <p>Now you have: <code>^b\d{3}</code></p> <blockquote> <p>followed by 'cv',</p> </blockquote> <p>Literal matching again, now we have <code>^b\d{3}cv</code></p> <blockquote> <p>followed by two digits,</p> </blockquote> <p>We already covered this: <code>^b\d{3}cv\d{2}</code>.</p> <blockquote> <p>then an underscore, followed by 'release', followed by .'ext'</p> </blockquote> <p>Again, this should all match literally, but the dot (<code>.</code>) is a special character. This means you have to escape it with a backslash: <code>^\d{3}cv\d{2}_release\.ext</code></p> <p>Leaving out the backslash would mean that a filename like "b410cv11_test_ext" would also match, which may or may not be a problem for you.</p> <p>Finally, if you want to guarantee that there is nothing else following ".ext", anchor the re to the end of the thing to match, use the dollar sign (<code>$</code>).</p> <p>Thus the complete regular expression for your specific problem would be:</p> <pre><code>^b\d{3}cv\d{2}_release\.ext$ </code></pre> <p>Easy.</p> <p>Whatever language or library you use, there has to be a reference somewhere in the documentation that will show you what the exact syntax in your case should be. Once you have learned to break down the problem into a suitable description, understanding the more advanced constructs will come to you step by step.</p>
11
2008-11-22T11:09:25Z
[ "python", "regex" ]
How do you compile wxPython under cygwin?
310,224
<p>I am using CYGWIN as a platform and would like to use wxPython. Is there a way to get the source compiled and working in cygwin?</p>
4
2008-11-21T21:18:01Z
310,365
<p>You would need a full working X environment to get it to work. It would be much easier to just use Python and wxPython under plain vanilla Windows. Do you have a special case?</p>
3
2008-11-21T22:04:01Z
[ "python", "installation", "wxpython", "cygwin", "compilation" ]
How do you compile wxPython under cygwin?
310,224
<p>I am using CYGWIN as a platform and would like to use wxPython. Is there a way to get the source compiled and working in cygwin?</p>
4
2008-11-21T21:18:01Z
4,467,468
<p>Isn't the whole point of using wxPython being to use WxWidgets? Isn't the whole point of using THAT being to have a cross platform GUI library?</p> <p>In other words, forget about X11, and just use the native wxPython on windows.</p> <p>If you want to avoid requiring the user to install wxPython and its dependencies, consider writing an installer. Alternatively, investigate py2exe to "compile" python to an .exe file (plus supporting .zip and .dll files), which is much more ammendable to "installing by merely copying files".</p>
0
2010-12-17T03:42:13Z
[ "python", "installation", "wxpython", "cygwin", "compilation" ]
How do you compile wxPython under cygwin?
310,224
<p>I am using CYGWIN as a platform and would like to use wxPython. Is there a way to get the source compiled and working in cygwin?</p>
4
2008-11-21T21:18:01Z
8,617,653
<p>I found this link to <a href="http://gnuradio.org/redmine/projects/gnuradio/wiki/WxPythonCygwin">build wxPython under Cygwin</a>. To me this is a much better option than installing all the X11 stuff. I tried it out using wxPython-src-2.8.12.1, and following the instructions to a tee, it worked perfectly.</p>
5
2011-12-23T15:21:18Z
[ "python", "installation", "wxpython", "cygwin", "compilation" ]
How do you compile wxPython under cygwin?
310,224
<p>I am using CYGWIN as a platform and would like to use wxPython. Is there a way to get the source compiled and working in cygwin?</p>
4
2008-11-21T21:18:01Z
11,237,925
<p>I tried another solution for using wxPython in cygwin:</p> <ol> <li>I installed python27 and wxPython in Windows7</li> <li>Did "echo 'export PATH=/cygdrive/c/Python27/:$PATH'>>~/.bashrc"</li> <li>Restart cygwin</li> </ol> <p>It works. Cheer!</p> <p>I don't know if any other Path should be added, but my program was executed on Fedora and it works on there. &nbsp;</p>
0
2012-06-28T04:05:39Z
[ "python", "installation", "wxpython", "cygwin", "compilation" ]
Adding a dimension to every element of a numpy.array
310,459
<p>I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:</p> <pre><code>&gt;&gt;&gt; my_ar = numpy.array((0,5,10)) [0, 5, 10] &gt;&gt;&gt; transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) &gt;&gt;&gt; transformed.shape (3, 3) </code></pre> <p>I've tried:</p> <pre><code>def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) </code></pre> <p>but get:</p> <pre><code>my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) </code></pre> <p>and I've tried:</p> <pre><code>my_fun = numpy.frompyfunc(my_fun_e, 1, 1) </code></pre> <p>but get:</p> <pre><code>&gt;&gt;&gt; my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) </code></pre> <p>This is close, but not quite right -- I get an array of objects, not an array of ints.</p> <p><b>Update 3!</b> OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?</p>
3
2008-11-21T22:44:41Z
310,493
<p>I propose:</p> <pre><code> numpy.resize(my_ar, (3,3)).transpose() </code></pre> <p>You can of course adapt the shape <code>(my_ar.shape[0],)*2</code> or whatever</p>
1
2008-11-21T22:59:33Z
[ "python", "arrays", "numpy" ]
Adding a dimension to every element of a numpy.array
310,459
<p>I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:</p> <pre><code>&gt;&gt;&gt; my_ar = numpy.array((0,5,10)) [0, 5, 10] &gt;&gt;&gt; transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) &gt;&gt;&gt; transformed.shape (3, 3) </code></pre> <p>I've tried:</p> <pre><code>def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) </code></pre> <p>but get:</p> <pre><code>my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) </code></pre> <p>and I've tried:</p> <pre><code>my_fun = numpy.frompyfunc(my_fun_e, 1, 1) </code></pre> <p>but get:</p> <pre><code>&gt;&gt;&gt; my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) </code></pre> <p>This is close, but not quite right -- I get an array of objects, not an array of ints.</p> <p><b>Update 3!</b> OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?</p>
3
2008-11-21T22:44:41Z
310,893
<p>Does this do what you want:</p> <pre><code>tile(my_ar, (1,1,3)) </code></pre>
1
2008-11-22T05:03:33Z
[ "python", "arrays", "numpy" ]
Adding a dimension to every element of a numpy.array
310,459
<p>I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:</p> <pre><code>&gt;&gt;&gt; my_ar = numpy.array((0,5,10)) [0, 5, 10] &gt;&gt;&gt; transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) &gt;&gt;&gt; transformed.shape (3, 3) </code></pre> <p>I've tried:</p> <pre><code>def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) </code></pre> <p>but get:</p> <pre><code>my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) </code></pre> <p>and I've tried:</p> <pre><code>my_fun = numpy.frompyfunc(my_fun_e, 1, 1) </code></pre> <p>but get:</p> <pre><code>&gt;&gt;&gt; my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) </code></pre> <p>This is close, but not quite right -- I get an array of objects, not an array of ints.</p> <p><b>Update 3!</b> OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?</p>
3
2008-11-21T22:44:41Z
313,427
<p>Does numpy.dstack do what you want? The first two indexes are the same as the original array, and the new third index is "depth".</p> <pre><code>&gt;&gt;&gt; import numpy as N &gt;&gt;&gt; a = N.array([[1,2,3],[4,5,6],[7,8,9]]) &gt;&gt;&gt; a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) &gt;&gt;&gt; b = N.dstack((a,a,a)) &gt;&gt;&gt; b array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]], [[7, 7, 7], [8, 8, 8], [9, 9, 9]]]) &gt;&gt;&gt; b[1,1] array([5, 5, 5]) </code></pre>
5
2008-11-24T04:45:11Z
[ "python", "arrays", "numpy" ]
Adding a dimension to every element of a numpy.array
310,459
<p>I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:</p> <pre><code>&gt;&gt;&gt; my_ar = numpy.array((0,5,10)) [0, 5, 10] &gt;&gt;&gt; transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) &gt;&gt;&gt; transformed.shape (3, 3) </code></pre> <p>I've tried:</p> <pre><code>def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) </code></pre> <p>but get:</p> <pre><code>my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) </code></pre> <p>and I've tried:</p> <pre><code>my_fun = numpy.frompyfunc(my_fun_e, 1, 1) </code></pre> <p>but get:</p> <pre><code>&gt;&gt;&gt; my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) </code></pre> <p>This is close, but not quite right -- I get an array of objects, not an array of ints.</p> <p><b>Update 3!</b> OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?</p>
3
2008-11-21T22:44:41Z
318,869
<p>Use map to apply your transformation function to each element in my_ar:</p> <pre><code>import numpy my_ar = numpy.array((0,5,10)) print my_ar transformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar)) print transformed print transformed.shape </code></pre>
1
2008-11-25T21:06:54Z
[ "python", "arrays", "numpy" ]
Python Input/Output, files
310,629
<p>I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.</p> <p>In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.</p> <p>Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?</p>
4
2008-11-22T00:31:32Z
310,635
<p>The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with <a href="http://docs.python.org/library/stringio.html" rel="nofollow">StringIO</a>:</p> <pre><code>from cStringIO import StringIO s = "My very long string I want to read like a file" file_like_string = StringIO(s) data = file_like_string.read(10) </code></pre> <p>Remember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file.</p>
10
2008-11-22T00:38:24Z
[ "python" ]
Python Input/Output, files
310,629
<p>I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.</p> <p>In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.</p> <p>Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?</p>
4
2008-11-22T00:31:32Z
311,650
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-pickle.html" rel="nofollow">Pickle and cPickle</a> modules may also be helpful to you.</p>
0
2008-11-22T19:01:04Z
[ "python" ]
In Django, how does one filter a QuerySet with dynamic field lookups?
310,732
<p>Given a class:</p> <pre><code>from django.db import models class Person(models.Model): name = models.CharField(max_length=20) </code></pre> <p>Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:</p> <pre><code> # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_value = 'B' # ... that you can run the equivalent of this? Person.objects.filter(filter_by=filter_value) # ... which will throw an exception, since `filter_by` is not # an attribute of `Person`. </code></pre> <p>Help is much appreciated &amp; thank you in advance.</p>
97
2008-11-22T02:06:06Z
310,775
<p>A really complex search forms usually indicates that a simpler model is trying to dig it's way out.</p> <p>How, exactly, do you expect to get the values for the column name and operation? Where do you get the values of <code>'name'</code> an <code>'startswith'</code>?</p> <pre><code> filter_by = '%s__%s' % ('name', 'startswith') </code></pre> <ol> <li><p>A "search" form? You're going to -- what? -- pick the name from a list of names? Pick the operation from a list of operations? While open-ended, most people find this confusing and hard-to-use.</p> <p>How many columns have such filters? 6? 12? 18? </p> <ul> <li>A few? A complex pick-list doesn't make sense. A few fields and a few if-statements make sense.</li> <li>A large number? Your model doesn't sound right. It sounds like the "field" is actually a key to a row in another table, not a column.</li> </ul></li> <li><p>Specific filter buttons. Wait... That's the way the Django admin works. Specific filters are turned into buttons. And the same analysis as above applies. A few filters make sense. A large number of filters usually means a kind of first normal form violation.</p></li> </ol> <p>A lot of similar fields often means there should have been more rows and fewer fields.</p>
-1
2008-11-22T02:36:56Z
[ "python", "django", "django-models" ]
In Django, how does one filter a QuerySet with dynamic field lookups?
310,732
<p>Given a class:</p> <pre><code>from django.db import models class Person(models.Model): name = models.CharField(max_length=20) </code></pre> <p>Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:</p> <pre><code> # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_value = 'B' # ... that you can run the equivalent of this? Person.objects.filter(filter_by=filter_value) # ... which will throw an exception, since `filter_by` is not # an attribute of `Person`. </code></pre> <p>Help is much appreciated &amp; thank you in advance.</p>
97
2008-11-22T02:06:06Z
310,785
<p>Python's argument expansion may be used to solve this problem:</p> <pre><code>kwargs = { '{0}__{1}'.format('name', 'startswith'): 'A', '{0}__{1}'.format('name', 'endswith'): 'Z' } Person.objects.filter(**kwargs) </code></pre> <p>This is a very common and useful Python idiom.</p>
170
2008-11-22T02:48:30Z
[ "python", "django", "django-models" ]
In Django, how does one filter a QuerySet with dynamic field lookups?
310,732
<p>Given a class:</p> <pre><code>from django.db import models class Person(models.Model): name = models.CharField(max_length=20) </code></pre> <p>Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:</p> <pre><code> # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_value = 'B' # ... that you can run the equivalent of this? Person.objects.filter(filter_by=filter_value) # ... which will throw an exception, since `filter_by` is not # an attribute of `Person`. </code></pre> <p>Help is much appreciated &amp; thank you in advance.</p>
97
2008-11-22T02:06:06Z
659,419
<p>A simplified example: </p> <p>In a Django survey app, I wanted an HTML select list showing registered users. But because we have 5000 registered users, I needed a way to filter that list based on query criteria (such as just people who completed a certain workshop). In order for the survey element to be re-usable, I needed for the person creating the survey question to be able to attach those criteria to that question (don't want to hard-code the query into the app). </p> <p>The solution I came up with isn't 100% user friendly (requires help from a tech person to create the query) but it does solve the problem. When creating the question, the editor can enter a dictionary into a custom field, e.g.:</p> <pre><code>{'is_staff':True,'last_name__startswith':'A',} </code></pre> <p>That string is stored in the database. In the view code, it comes back in as <code>self.question.custom_query</code> . The value of that is a string that <em>looks</em> like a dictionary. We turn it back into a <em>real</em> dictionary with eval() and then stuff it into the queryset with **kwargs:</p> <pre><code>kwargs = eval(self.question.custom_query) user_list = User.objects.filter(**kwargs).order_by("last_name") </code></pre>
6
2009-03-18T17:52:22Z
[ "python", "django", "django-models" ]
In Django, how does one filter a QuerySet with dynamic field lookups?
310,732
<p>Given a class:</p> <pre><code>from django.db import models class Person(models.Model): name = models.CharField(max_length=20) </code></pre> <p>Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:</p> <pre><code> # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_value = 'B' # ... that you can run the equivalent of this? Person.objects.filter(filter_by=filter_value) # ... which will throw an exception, since `filter_by` is not # an attribute of `Person`. </code></pre> <p>Help is much appreciated &amp; thank you in advance.</p>
97
2008-11-22T02:06:06Z
16,718,559
<p><a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects" rel="nofollow">Django.db.models.Q</a> is exactly what you want in a Django way.</p>
4
2013-05-23T15:55:36Z
[ "python", "django", "django-models" ]
Python library to modify MP3 audio without transcoding
310,765
<p>I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.</p> <p>My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise).</p> <p>I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.)</p> <p>My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.)</p> <p>I <em>conjecture</em> that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds.</p> <p>I have looked at <a href="http://pymedia.org/">PyMedia</a>, but it requires me to migrate to PCM to process the data. Similarly, <a href="http://lame.sourceforge.net">LAME</a> wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags.</p> <p>Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?</p>
16
2008-11-22T02:30:54Z
310,792
<p>Mp3 is lossy, but it is lossy in a very specific way. The algorithms used as designed to discard certain parts of the audio which your ears are unable to hear (or are very difficult to hear). Re-doing the compression process at the same level of compression over and over is likely to yield <em>nearly</em> identical results for a given piece of audio. However, some additional losses may slowly accumulate. If you're going to be modifying files a lot, this might be a bad idea. It would also be a bad idea if you were concerned about quality, but then using MP3 if you are concerned about quality is a bad idea over all.</p> <p>You could construct a test using an encoder and a decoder to re-encode a few different mp3 files a few times and watch how they change, this could help you determine the rate of deterioration and figure out if it is acceptable to you. Sounds like you have libraries you could use to run this simple test already.</p> <p>MP3 files are composed of "frames" of audio and so it should be possible, with some effort, to remove entire frames with minimal processing (remove the frame, update some minor details in the file header). I believe frames are pretty short (a few milliseconds each) which would give the precision you're looking for. So doing some reading on the <a href="http://en.wikipedia.org/wiki/Image:Mp3filestructure.svg" rel="nofollow">MP3 File Format</a> should give you enough information to code your own python library to do this. This is a fair bit different than traditional "audio processing" (since you don't care about precision) and so you're unlikely to find an existing library that does this. Most, as you've found, will decompress the audio first so you can have complete fine-grained control.</p>
3
2008-11-22T03:01:08Z
[ "python", "mp3", "codec" ]