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
listlengths
1
5
key=operator.attrgetter sort order?
1,129,548
<p>in my django view, if i import operator, and use the following code:</p> <pre><code>multitags = sorted(multitags, key=operator.attrgetter('date_added')) </code></pre> <p>is there an easy way to reverse the order – such that i get the dates in descending order (today at top; last week underneath)?</p>
1
2009-07-15T05:27:26Z
1,129,558
<p>This should work:</p> <pre><code>sorted(multitags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>This document on the python wiki is worth reading through at least once to get an idea of other things worth knowing:</p> <ul> <li><a href="http://wiki.python.org/moin/HowTo/Sorting">Sorting Mini HOWTO</a></li> </ul>
7
2009-07-15T05:29:49Z
[ "python", "django", "itertools" ]
key=operator.attrgetter sort order?
1,129,548
<p>in my django view, if i import operator, and use the following code:</p> <pre><code>multitags = sorted(multitags, key=operator.attrgetter('date_added')) </code></pre> <p>is there an easy way to reverse the order – such that i get the dates in descending order (today at top; last week underneath)?</p>
1
2009-07-15T05:27:26Z
1,129,561
<p>Sure, just add <code>reverse=True</code> to the keyword arguments with which you're calling <code>.sorted</code>!</p>
2
2009-07-15T05:30:32Z
[ "python", "django", "itertools" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,129,732
<p>Third time's the charm:</p> <pre><code>def perm(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result </code></pre>
5
2009-07-15T06:32:10Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,129,736
<p>What you're doing is close to a conversion from base 10 (your number) to base 6, with ABCDEF being your digits. The only difference is "AA" and "A" are different, which is wrong if you consider "A" the zero-digit.</p> <p>If you add the next greater power of six to your number, and then do a base conversion to base 6 using these digits, and finally strip the first digit (which should be a "B", i.e. a "1"), you've got the result.</p> <p>I just want to post an idea here, not an implementation, because the question smells a lot like homework to me (I do give the benefit of the doubt; it's just my feeling).</p>
3
2009-07-15T06:32:57Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,129,765
<p>Multi-radix solution at the bottom.</p> <pre><code>import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) values = "ABCDEF" for i in range(0, 100): chars, n = idx_to_length_and_value(i, len(values)) print "".join(conv_base(chars, n, values)) </code></pre> <p><hr /></p> <pre><code>import math def get_max_value_for_digits(digits_list): max_vals = [] for val in digits_list: val = len(val) if max_vals: val *= max_vals[-1] max_vals.append(val) return max_vals def idx_to_length_and_value(n, digits_list): chars = 1 max_vals = get_max_value_for_digits(digits_list) while True: if chars-1 &gt;= len(max_vals): raise OverflowError, "number not representable" max_val = max_vals[chars-1] if n &lt; max_val: return chars, n chars += 1 n -= max_val def conv_base(chars, n, digits_list): ret = [] for i in range(chars-1, -1, -1): digits = digits_list[i] radix = len(digits) c = digits[n % len(digits)] ret.append(c) n /= radix return reversed(ret) digits_list = ["ABCDEF", "ABC", "AB"] for i in range(0, 120): chars, n = idx_to_length_and_value(i, digits_list) print "".join(conv_base(chars, n, digits_list)) </code></pre>
5
2009-07-15T06:40:49Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,130,119
<p>First compute the length by summing up powers of six until you exceed your index (or better use the formula for the geometric series).</p> <p>Subtract the sum of smaller powers from the index.</p> <p>Compute the representation to base 6, fill leading zeros and map 0 -> A, ..., 5 -> F.</p>
2
2009-07-15T08:28:58Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,130,268
<pre><code>alphabet = 'ABCDEF' def idx_to_excel_column_name(x): x += 1 # Make us skip "" as a valid word group_size = 1 for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) def excel_column_name_to_idx(name): q = len(alphabet) x = 0 for letter in name: x *= q x += alphabet.index(letter) return x+q**len(name)//(q-1)-1 </code></pre>
1
2009-07-15T09:08:38Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,130,312
<p>In perl you'd just convert your input i from base(10) to base(length of "ABCDEF"), then do a <code>tr/012345/ABCDEF/</code> which is the same as <code>y/0-5/A-F/</code>. Surely Python has a similar feature set.</p> <p>Oh, as pointed out by <a href="http://stackoverflow.com/users/40916/yairchu">Yarichu</a> the combinations are a tad different because if A represented 0, then there would be no combinations with leading A (though he said it a bit different). It seems I thought the problem to be more trivial than it is. You cannot just transliterate different base numbers, because numbers containing the equivalent of 0 would be skipped in the sequence.</p> <p>So what I suggested is actually only the last step of what <a href="http://stackoverflow.com/users/49246/starblue">starblue</a> <a href="#1130119" rel="nofollow">suggested</a>, which is essentially what <a href="http://stackoverflow.com/users/90848/laurence-gonsalves">Laurence Gonsalves</a> <a href="#1129732" rel="nofollow">implemented</a> ftw. Oh, and there is no transliteration (<code>tr//</code> or <code>y//</code>) operation in Python, what a shame.</p>
0
2009-07-15T09:21:09Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,130,907
<p>Since we are <strong>converting</strong> from a number Base(10) to a number Base(7), whilst avoiding all "0" in the output, we will have to adjust the orginal number, so we do skip by one every time the result would contain a "0".</p> <pre><code> 1 =&gt; A, or 1 in base [0ABCDEF] 7 =&gt; AA, or 8 in base [0ABCDEF] 13 =&gt; BA, or 15 in base [0ABCDEF] 42 =&gt; FF, or 48 in base [0ABCDEF] 43 =&gt;AAA, or 50 in base [0ABCDEF] </code></pre> <p>Here's some Perl code that shows what I'm trying to explain (sorry, didn't see this is a Python request)</p> <pre><code>use strict; use warnings; my @Symbols=qw/0 A B C D E F/; my $BaseSize=@Symbols ; for my $NR ( 1 .. 45) { printf ("Convert %3i =&gt; %s\n",$NR ,convert($NR)); } sub convert { my ($nr,$res)=@_; return $res unless $nr&gt;0; $res="" unless defined($res); #Adjust to skip '0' $nr=$nr + int(($nr-1)/($BaseSize-1)); return convert(int($nr/$BaseSize),$Symbols[($nr % ($BaseSize))] . $res); } </code></pre>
1
2009-07-15T11:42:32Z
[ "python", "combinatorics" ]
How to produce the i-th combination/permutation without iterating
1,129,704
<p>Given any iterable, for example: "ABCDEF"</p> <p>Treating it almost like a numeral system as such:</p> <p>A B C D E F AA AB AC AD AE AF BA BB BC .... FF AAA AAB ....</p> <p>How would I go about finding the i<sup>th</sup> member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.</p> <p>Nice, but not required: Could the solution be generalized for pseudo-<a href="http://en.wikipedia.org/wiki/Mixed_radix" rel="nofollow">"mixed radix"</a> system?</p> <p>--- RESULTS ---</p> <pre><code># ------ paul ----- def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] # ----- Glenn Maynard ----- import math def idx_to_length_and_value(n, length): chars = 1 while True: cnt = pow(length, chars) if cnt &gt; n: return chars, n chars += 1 n -= cnt def conv_base(chars, n, values): ret = [] for i in range(0, chars): c = values[n % len(values)] ret.append(c) n /= len(values) return reversed(ret) def f1(i, values = "ABCDEF"): chars, n = idx_to_length_and_value(i, len(values)) return "".join(conv_base(chars, n, values)) # -------- Laurence Gonsalves ------ def f2(i, seq): seq = tuple(seq) n = len(seq) max = n # number of perms with 'digits' digits digits = 1 last_max = 0 while i &gt;= max: last_max = max max = n * (max + 1) digits += 1 result = '' i -= last_max while digits: digits -= 1 result = seq[i % n] + result i //= n return result # -------- yairchu ------- def f3(x, alphabet = 'ABCDEF'): x += 1 # Make us skip "" as a valid word group_size = 1 num_letters = 0 while 1: #for num_letters in itertools.count(): if x &lt; group_size: break x -= group_size group_size *= len(alphabet) num_letters +=1 letters = [] for i in range(num_letters): x, m = divmod(x, len(alphabet)) letters.append(alphabet[m]) return ''.join(reversed(letters)) # ----- testing ---- import time import random tries = [random.randint(1,1000000000000) for i in range(10000)] numbs = 'ABCDEF' time0 = time.time() s0 = [f1(i, numbs) for i in tries] print 's0 paul',time.time()-time0, 'sec' time0 = time.time() s1 = [f1(i, numbs) for i in tries] print 's1 Glenn Maynard',time.time()-time0, 'sec' time0 = time.time() s2 = [f2(i, numbs) for i in tries] print 's2 Laurence Gonsalves',time.time()-time0, 'sec' time0 = time.time() s3 = [f3(i,numbs) for i in tries] print 's3 yairchu',time.time()-time0, 'sec' </code></pre> <p>times: </p> <pre><code>s0 paul 0.470999956131 sec s1 Glenn Maynard 0.472999811172 sec s2 Laurence Gonsalves 0.259000062943 sec s3 yairchu 0.325000047684 sec &gt;&gt;&gt; s0==s1==s2==s3 True </code></pre>
9
2009-07-15T06:22:31Z
1,140,819
<p>This works (and is what i finally settled on), and thought it was worth posting because it is tidy. However it is slower than most answers. Can i perform % and / in the same operation?</p> <pre><code>def f0(x, alph='ABCDE'): result = '' ct = len(alph) while x&gt;=0: result += alph[x%ct] x /= ct-1 return result[::-1] </code></pre>
2
2009-07-16T23:29:30Z
[ "python", "combinatorics" ]
Django: reverse function fails with an exception
1,129,769
<p>I'm following the Django tutorial and got stuck with an error at part 4 of the tutorial. I got to the part where I'm writing the <em>vote</em> view, which uses <em>reverse</em> to redirect to another view. For some reason, reverse fails with the following exception:</p> <blockquote> <p><strong>import</strong>() argument 1 must be string, not instancemethod</p> </blockquote> <p>Currently my project's urls.py looks like this:</p> <pre><code>from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^polls/', include('mysite.polls.urls')), (r'^admin/(.*)', include(admin.site.root)), ) </code></pre> <p>and the app urls.py is:</p> <pre><code>from django.conf.urls.defaults import * urlpatterns = patterns('mysite.polls.views', (r'^$', 'index'), (r'^(?P&lt;poll_id&gt;\d+)/$', 'details'), (r'^(?P&lt;poll_id&gt;\d+)/results/$', 'results'), (r'^(?P&lt;poll_id&gt;\d+)/vote/$', 'vote'), ) </code></pre> <p>And the vote view is: (I've simplified it to have only the row with the error)</p> <pre><code>def vote(request, poll_id): return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(1,))) </code></pre> <p>When I remove the admin urls include from the project's urls.py, i.e. making it into:</p> <pre><code>urlpatterns = patterns('', (r'^polls/', include('mysite.polls.urls')), #(r'^admin/(.*)', include(admin.site.root)), ) </code></pre> <p>it works. </p> <p>I've tried so many things and can't understand what I'm doing wrong.</p>
3
2009-07-15T06:42:02Z
1,129,811
<p>The way you include the admin URLs has changed a few times over the last couple of versions. It's likely that you are using the wrong instructions for the version of Django you have installed.</p> <p>If you are using the current trunk - ie not an official release - then the documentation at <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">http://docs.djangoproject.com/en/dev/</a> is correct.</p> <p>However, if you are using 1.0.2 then you should follow the link at the top of the page to <a href="http://docs.djangoproject.com/en/1.0/" rel="nofollow">http://docs.djangoproject.com/en/1.0/</a>.</p>
6
2009-07-15T06:54:53Z
[ "python", "django", "admin", "reverse" ]
Creating a decorator in a class with access to the (current) class itself
1,129,821
<p>Currently, I'm doing it in this fashion:</p> <pre><code>class Spam(object): decorated = None @classmethod def decorate(cls, funct): if cls.decorated is None: cls.decorated = [] cls.decorated.append(funct) return funct class Eggs(Spam): pass @Eggs.decorate def foo(): print "spam and eggs" print Eggs.decorated # [&lt;function foo at 0x...&gt;] print Spam.decorated # None </code></pre> <p>I <strong>need</strong> to be able to do this in a subclass as shown. The problem is that I can't seem to figure out how to make the <code>decorated</code> field not shared between instances. Right now I have a hackish solution by initially setting it to <code>None</code> and then checking it when the function is decorated, but that only works one way. In other words, if I subclass <code>Eggs</code> and then decorate something with the <code>Eggs.decorate</code> function, it affects all subclasses. </p> <p>I guess my question is: is it possible to have mutable class fields that don't get shared between base and sub classes?</p>
0
2009-07-15T06:58:15Z
1,129,886
<p>I'm fairly sure you can't. I thought about doing this with property(), but unfortunately the class of the class itself--where a property would need to go--is ClassType itself.</p> <p>You can write your decorator like this, but it changes the interface a little:</p> <pre><code>class Spam(object): decorated = {} @classmethod def get_decorated_methods(cls): return cls.decorated.setdefault(cls, []) @classmethod def decorate(cls, funct): cls.get_decorated_methods().append(funct) return funct class Eggs(Spam): pass @Spam.decorate def foo_and_spam(): print "spam" @Eggs.decorate def foo_and_eggs(): print "eggs" print Eggs.get_decorated_methods() # [&lt;function foo_and_eggs at 0x...&gt;] print Spam.get_decorated_methods() # [&lt;function foo_and_spam at 0x...&gt;] </code></pre>
0
2009-07-15T07:18:12Z
[ "python", "inheritance", "class", "decorator" ]
Creating a decorator in a class with access to the (current) class itself
1,129,821
<p>Currently, I'm doing it in this fashion:</p> <pre><code>class Spam(object): decorated = None @classmethod def decorate(cls, funct): if cls.decorated is None: cls.decorated = [] cls.decorated.append(funct) return funct class Eggs(Spam): pass @Eggs.decorate def foo(): print "spam and eggs" print Eggs.decorated # [&lt;function foo at 0x...&gt;] print Spam.decorated # None </code></pre> <p>I <strong>need</strong> to be able to do this in a subclass as shown. The problem is that I can't seem to figure out how to make the <code>decorated</code> field not shared between instances. Right now I have a hackish solution by initially setting it to <code>None</code> and then checking it when the function is decorated, but that only works one way. In other words, if I subclass <code>Eggs</code> and then decorate something with the <code>Eggs.decorate</code> function, it affects all subclasses. </p> <p>I guess my question is: is it possible to have mutable class fields that don't get shared between base and sub classes?</p>
0
2009-07-15T06:58:15Z
1,129,905
<p>I figured it out through using metaclasses. Thanks for all who posted. Here is my solution if anybody comes across a similar problem:</p> <pre><code>class SpamMeta(type): def __new__(cls, name, bases, dct): SpamType = type.__new__(cls, name, bases, dct) SpamType.decorated = [] return SpamType class Spam(object): __metaclass__ = SpamMeta @classmethod def decorate(cls, funct): cls.decorated.append(funct) return funct class Eggs(Spam): pass @Eggs.decorate def foo(): print "spam and eggs" print Eggs.decorated # [&lt;function foo at 0x...&gt;] print Spam.decorated # [] </code></pre>
1
2009-07-15T07:26:27Z
[ "python", "inheritance", "class", "decorator" ]
Creating a decorator in a class with access to the (current) class itself
1,129,821
<p>Currently, I'm doing it in this fashion:</p> <pre><code>class Spam(object): decorated = None @classmethod def decorate(cls, funct): if cls.decorated is None: cls.decorated = [] cls.decorated.append(funct) return funct class Eggs(Spam): pass @Eggs.decorate def foo(): print "spam and eggs" print Eggs.decorated # [&lt;function foo at 0x...&gt;] print Spam.decorated # None </code></pre> <p>I <strong>need</strong> to be able to do this in a subclass as shown. The problem is that I can't seem to figure out how to make the <code>decorated</code> field not shared between instances. Right now I have a hackish solution by initially setting it to <code>None</code> and then checking it when the function is decorated, but that only works one way. In other words, if I subclass <code>Eggs</code> and then decorate something with the <code>Eggs.decorate</code> function, it affects all subclasses. </p> <p>I guess my question is: is it possible to have mutable class fields that don't get shared between base and sub classes?</p>
0
2009-07-15T06:58:15Z
1,133,773
<p>Not that I have anything against metaclasses, but you can also solve it without them:</p> <pre><code>from collections import defaultdict class Spam(object): _decorated = defaultdict(list) @classmethod def decorate(cls, func): cls._decorated[cls].append(func) return func @classmethod def decorated(cls): return cls._decorated[cls] class Eggs(Spam): pass @Eggs.decorate def foo(): print "spam and eggs" print Eggs.decorated() # [&lt;function foo at 0x...&gt;] print Spam.decorated() # [] </code></pre> <p>It is not possible to have properties on class objects (unless you revert to metaclasses again), therefore it is mandatory to get the list of decorated methods via a classmethod again. There is an extra layer of indirection involved compared to the metaclass solution.</p>
0
2009-07-15T20:23:16Z
[ "python", "inheritance", "class", "decorator" ]
virtualenv with all Python libraries
1,130,402
<p>I need to get Python code, which relies on Python 2.6, running on a machine with only Python 2.3 (I have no root access).</p> <p>This is a typical scenario for virtualenv. The only problem is that I cannot convince it to copy all libraries to the new environment as well.</p> <pre><code>virtualenv --no-site-packages my_py26 </code></pre> <p>does not do what I need. The library files are still only links to the <code>/usr/lib/python2.6</code> directory.</p> <p>No I'm wondering, whether virtualenv is the right solution for this scenario at all. From what I understand it is only targetted to run on machines with exactly the same Python version. Tools like cx_Freeze and the like do not work for me, as I start the Python file after some environment variable tweeking. </p> <p>Is there maybe a hidden virtualenv option that copies all the Python library files into the new environment? Or some other tool that can help here?</p>
1
2009-07-15T09:40:01Z
1,130,443
<p>No, I think you completely misunderstood what virtualenv does. Virtualenv is to create a new environment <em>on the same machine</em> that is isolated from the main environment. In such an environment you can install packages that do not get installed in the main environment, and with --no-site-packages you can also isolate you from the main environments installed modules.</p> <p>If you need to run a program that requires Python 2.6 on a machine that does not have 2.6, you need to install Python 2.6 on that machine. </p>
4
2009-07-15T09:48:49Z
[ "python", "linux", "virtualenv" ]
virtualenv with all Python libraries
1,130,402
<p>I need to get Python code, which relies on Python 2.6, running on a machine with only Python 2.3 (I have no root access).</p> <p>This is a typical scenario for virtualenv. The only problem is that I cannot convince it to copy all libraries to the new environment as well.</p> <pre><code>virtualenv --no-site-packages my_py26 </code></pre> <p>does not do what I need. The library files are still only links to the <code>/usr/lib/python2.6</code> directory.</p> <p>No I'm wondering, whether virtualenv is the right solution for this scenario at all. From what I understand it is only targetted to run on machines with exactly the same Python version. Tools like cx_Freeze and the like do not work for me, as I start the Python file after some environment variable tweeking. </p> <p>Is there maybe a hidden virtualenv option that copies all the Python library files into the new environment? Or some other tool that can help here?</p>
1
2009-07-15T09:40:01Z
1,130,455
<p>I can't help you with your virtualenv problem as I have never used it. But I will just point something out for future use.</p> <p>You can install software from sources into your home folder and run them without root access. for example to install python 2.6:</p> <pre><code>~/src/Python-2.6.2 $ ./configure --prefix=$HOME/local ~/src/Python-2.6.2 $ make ... ~/src/Python-2.6.2 $ make install ... export PATH=$HOME/local/bin:$PATH export LD_LIBRARY_PATH=$HOME/local/lib:$LD_LIBRARY_PATH ~/src/Python-2.6.2 $ which python /home/name/local/bin/python </code></pre> <p>This is what I have used at Uni to install software where I don't have root access.</p>
4
2009-07-15T09:50:43Z
[ "python", "linux", "virtualenv" ]
virtualenv with all Python libraries
1,130,402
<p>I need to get Python code, which relies on Python 2.6, running on a machine with only Python 2.3 (I have no root access).</p> <p>This is a typical scenario for virtualenv. The only problem is that I cannot convince it to copy all libraries to the new environment as well.</p> <pre><code>virtualenv --no-site-packages my_py26 </code></pre> <p>does not do what I need. The library files are still only links to the <code>/usr/lib/python2.6</code> directory.</p> <p>No I'm wondering, whether virtualenv is the right solution for this scenario at all. From what I understand it is only targetted to run on machines with exactly the same Python version. Tools like cx_Freeze and the like do not work for me, as I start the Python file after some environment variable tweeking. </p> <p>Is there maybe a hidden virtualenv option that copies all the Python library files into the new environment? Or some other tool that can help here?</p>
1
2009-07-15T09:40:01Z
1,130,485
<p>You haven't clearly explained why <code>cx_Freeze</code> and the like wouldn't work for you. The normal approach to distributing Python applications to machines which have an older version of Python, or even no Python at all, is a tool like <a href="http://pyinstaller.org/" rel="nofollow">PyInstaller</a> (in the same class of tools as <code>cx_Freeze</code>). PyInstaller makes copies of all your dependencies and allows you to create a single executable file which contains all your Python dependencies.</p> <p>You mention tweaking environment variables as a reason why you can't use such tools; if you expand on exactly why this is, you may be able to get a more helpful answer.</p>
0
2009-07-15T09:57:38Z
[ "python", "linux", "virtualenv" ]
Get POST data from a complex Django form?
1,130,575
<p>I have a Django form that uses a different number of fields based on the year/month. So I create the fields in the form like this:</p> <pre><code>for entry in entry_list: self.fields[entry] = forms.DecimalField([stuffhere]) </code></pre> <p>but now I don't know how to get the submitted data from the form.</p> <p>Normally I would do something like:</p> <pre><code>form.cleaned_data["fieldname"] </code></pre> <p>but I don't know what the names of the fields are. The debug screen shows my POST data as simply "Entry Object" with a value of "u''". Calling POST.lists() doesn't show anything. </p> <p>I am sure I am missing something obvious, but I've been stuck on this for a few days too many. Is there a better way to do this? Is all of the data in the request object, but I just don't know how to use it?</p> <p>Here is the code for the model/form/view: <a href="http://pastebin.com/f28d92c0e" rel="nofollow">http://pastebin.com/f28d92c0e</a></p> <p>Much Thanks!</p> <p>EDIT:</p> <p>I've tried out both of the suggestions below. Using formsets was definitely easier and nicer. </p>
0
2009-07-15T10:22:06Z
1,130,681
<p>I think you might be better off using <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/" rel="nofollow">formsets</a> here. They're designed for exactly what you seem to be trying to do - dealing with a variable number of items within a form.</p>
5
2009-07-15T10:45:36Z
[ "python", "django", "django-forms" ]
Get POST data from a complex Django form?
1,130,575
<p>I have a Django form that uses a different number of fields based on the year/month. So I create the fields in the form like this:</p> <pre><code>for entry in entry_list: self.fields[entry] = forms.DecimalField([stuffhere]) </code></pre> <p>but now I don't know how to get the submitted data from the form.</p> <p>Normally I would do something like:</p> <pre><code>form.cleaned_data["fieldname"] </code></pre> <p>but I don't know what the names of the fields are. The debug screen shows my POST data as simply "Entry Object" with a value of "u''". Calling POST.lists() doesn't show anything. </p> <p>I am sure I am missing something obvious, but I've been stuck on this for a few days too many. Is there a better way to do this? Is all of the data in the request object, but I just don't know how to use it?</p> <p>Here is the code for the model/form/view: <a href="http://pastebin.com/f28d92c0e" rel="nofollow">http://pastebin.com/f28d92c0e</a></p> <p>Much Thanks!</p> <p>EDIT:</p> <p>I've tried out both of the suggestions below. Using formsets was definitely easier and nicer. </p>
0
2009-07-15T10:22:06Z
1,130,719
<p>In this line:</p> <blockquote> <p>self.fields[entry] = forms.DecimalField(max_digits=4, decimal_places=1, label=nice_label)</p> </blockquote> <p>entry is a model instance. But fields are keyed by field names (strings). Try something like:</p> <blockquote> <p>self.fields[entry.entry_name] = forms.Decimal(...)</p> </blockquote> <p>(substitute appropriate for "entry_name").</p>
0
2009-07-15T10:55:16Z
[ "python", "django", "django-forms" ]
Encryption with Python
1,130,687
<p>I'm making an encryption function in Python and I want to encrypt a random number using a public key.</p> <p>I wish to know that if I use Crypto package (<code>Crypto.publicKey.pubkey</code>) than how can I use the method like...</p> <pre><code>def encrypt(self,plaintext,k) </code></pre> <p>Here the <code>k</code> is itself a random number, is this mean the key. Can somebody help me with somewhat related?</p>
1
2009-07-15T10:47:52Z
1,130,702
<p>hi you can try <a href="http://www.pycrypto.org/" rel="nofollow">Pycrypto</a>.</p>
3
2009-07-15T10:51:20Z
[ "python", "encryption", "cryptography" ]
Encryption with Python
1,130,687
<p>I'm making an encryption function in Python and I want to encrypt a random number using a public key.</p> <p>I wish to know that if I use Crypto package (<code>Crypto.publicKey.pubkey</code>) than how can I use the method like...</p> <pre><code>def encrypt(self,plaintext,k) </code></pre> <p>Here the <code>k</code> is itself a random number, is this mean the key. Can somebody help me with somewhat related?</p>
1
2009-07-15T10:47:52Z
1,131,051
<p>Are you trying to encrypt a session/message key for symmetric encryption using the public key of the recipient? It might be more straightforward to use, say, SSH or TLS in those cases.</p> <p>Back to your question:</p> <p><a href="http://chandlerproject.org/bin/view/Projects/MeTooCrypto" rel="nofollow">Me Too Crypto</a> (M2Crypto) is a nice wrapper around openssl.</p> <p>First, you need to get the public key of the recipient:</p> <pre><code>recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read()) </code></pre> <p>Now you can encrypt your message:</p> <pre><code>plaintext = random_integer_you_want_to_encrypt msg = recip.public_encrypt(plaintext,RSA.pkcs1_padding) </code></pre> <p>Now only someone with the <em>private</em> key of the recipient can decrypt it.</p>
4
2009-07-15T12:17:50Z
[ "python", "encryption", "cryptography" ]
Encryption with Python
1,130,687
<p>I'm making an encryption function in Python and I want to encrypt a random number using a public key.</p> <p>I wish to know that if I use Crypto package (<code>Crypto.publicKey.pubkey</code>) than how can I use the method like...</p> <pre><code>def encrypt(self,plaintext,k) </code></pre> <p>Here the <code>k</code> is itself a random number, is this mean the key. Can somebody help me with somewhat related?</p>
1
2009-07-15T10:47:52Z
1,136,214
<p>The value k that you pass to encrypt is not part of the key. k is a random value that is used to randomize the encryption. It should be a different random number every time you encrypt a message. </p> <p>Unfortunately, depending on what public key algorithm you use this k needs to satisfy more or less strict conditions. I.e., your encryption may be completely insecure if k does not contain enough entropy. This makes using pycrypto difficult, because you need to know more about the cryptosystem you use than the developer of the library. In my opinion this is a serious flaw of pycrypto and I'd recommend that you use a more high level crypto library that doesn't require that you know any such details. (i.e. something like M2Crypto)</p>
0
2009-07-16T08:35:11Z
[ "python", "encryption", "cryptography" ]
Jython or JRuby?
1,130,697
<p>It's a high level conceptual question. I have two separate code bases that serve the same purpose, one built in Python and the other in Ruby. I need to develop something that will run on JVM. So I have two choices: convert the Python code to Jython or convert the Ruby to JRuby. Since I don't know any of them, I was wondering if anyone can give me some guidance. Like which one runs faster, or more importantly which one has tools available for easy code migration(.pyc to .jar files)?</p>
4
2009-07-15T10:50:04Z
1,130,722
<p>In both cases, most of the code should Just Work&trade;. I don't know of a really compelling reason to choose Jython over JRuby or vice versa if you'll be learning either from scratch. Python places a heavy emphasis on readability and not using "magic", but Ruby tends to give you a little more rope to do fancy things, e.g., define your own DSL. The main difference is in the community, and largely revolves around the different focus mentioned above.</p>
5
2009-07-15T10:55:47Z
[ "python", "ruby", "jruby", "jython" ]
Jython or JRuby?
1,130,697
<p>It's a high level conceptual question. I have two separate code bases that serve the same purpose, one built in Python and the other in Ruby. I need to develop something that will run on JVM. So I have two choices: convert the Python code to Jython or convert the Ruby to JRuby. Since I don't know any of them, I was wondering if anyone can give me some guidance. Like which one runs faster, or more importantly which one has tools available for easy code migration(.pyc to .jar files)?</p>
4
2009-07-15T10:50:04Z
1,130,727
<p>The compatibility in either case is at the source-code level; with necessary changes where the Python or Ruby code invokes packages that involve native code (especially, standard Python packages like ctypes are not present in Jython).</p>
1
2009-07-15T10:56:44Z
[ "python", "ruby", "jruby", "jython" ]
Jython or JRuby?
1,130,697
<p>It's a high level conceptual question. I have two separate code bases that serve the same purpose, one built in Python and the other in Ruby. I need to develop something that will run on JVM. So I have two choices: convert the Python code to Jython or convert the Ruby to JRuby. Since I don't know any of them, I was wondering if anyone can give me some guidance. Like which one runs faster, or more importantly which one has tools available for easy code migration(.pyc to .jar files)?</p>
4
2009-07-15T10:50:04Z
1,130,948
<p>If you are going to be investing time and effort into either platform you should check how active the development is on both platforms. Subscribe to the mailing lists and newsgroups to get an idea of the community, check the source control system for both projects and get a feeling for how active the development is.</p> <p>I am more familiar with Python than Ruby. The Jython project after a period slow movement has really picked up momentum, a Python 2.5 compatible version was released in June. This is a major step forward as Python 2.5 introduces some very useful language enhancements: <a href="http://docs.python.org/whatsnew/2.5.html" rel="nofollow">http://docs.python.org/whatsnew/2.5.html</a></p>
2
2009-07-15T11:54:38Z
[ "python", "ruby", "jruby", "jython" ]
Jython or JRuby?
1,130,697
<p>It's a high level conceptual question. I have two separate code bases that serve the same purpose, one built in Python and the other in Ruby. I need to develop something that will run on JVM. So I have two choices: convert the Python code to Jython or convert the Ruby to JRuby. Since I don't know any of them, I was wondering if anyone can give me some guidance. Like which one runs faster, or more importantly which one has tools available for easy code migration(.pyc to .jar files)?</p>
4
2009-07-15T10:50:04Z
1,130,986
<p>Performance may be the deciding factor: in <a href="http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/" rel="nofollow">this benchmark</a> (which, like all benchmarks, should be taken with a grain of salt), JRuby ran somewaht faster than native Ruby, while Jython was outperformed by CPython by a factor of 3.</p>
1
2009-07-15T12:03:00Z
[ "python", "ruby", "jruby", "jython" ]
Jython or JRuby?
1,130,697
<p>It's a high level conceptual question. I have two separate code bases that serve the same purpose, one built in Python and the other in Ruby. I need to develop something that will run on JVM. So I have two choices: convert the Python code to Jython or convert the Ruby to JRuby. Since I don't know any of them, I was wondering if anyone can give me some guidance. Like which one runs faster, or more importantly which one has tools available for easy code migration(.pyc to .jar files)?</p>
4
2009-07-15T10:50:04Z
1,140,847
<p>Anything you can do in one, you can do in the other. </p> <p>Learn enough of both to realise which one appeals to your coding sensibilities. There is no right or wrong answer here.</p>
1
2009-07-16T23:41:31Z
[ "python", "ruby", "jruby", "jython" ]
which exception catches xxxx error in python
1,130,764
<p>given a traceback error log, i don't always know how to catch a particular exception.</p> <p>my question is in general, how do i determine which "except" clause to write in order to handle a certain exception.</p> <p>example 1:</p> <pre><code> File "c:\programs\python\lib\httplib.py", line 683, in connect raise socket.error, msg error: (10065, 'No route to host') </code></pre> <p>example 2:</p> <pre><code>return codecs.charmap_encode(input,errors,encoding_table) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position(...) </code></pre> <p>catching the 2nd example is obvious:</p> <pre><code>try: ... except UnicodeDecodeError: ... </code></pre> <p>how do i catch specifically the first error?</p>
5
2009-07-15T11:04:53Z
1,130,767
<p>Look at the stack trace. The code that raises the exception is: <code>raise socket.error, msg</code>.</p> <p>So the answer to your question is: You have to catch <code>socket.error</code>.</p> <pre><code>import socket ... try: ... except socket.error: ... </code></pre>
4
2009-07-15T11:06:31Z
[ "python", "exception" ]
which exception catches xxxx error in python
1,130,764
<p>given a traceback error log, i don't always know how to catch a particular exception.</p> <p>my question is in general, how do i determine which "except" clause to write in order to handle a certain exception.</p> <p>example 1:</p> <pre><code> File "c:\programs\python\lib\httplib.py", line 683, in connect raise socket.error, msg error: (10065, 'No route to host') </code></pre> <p>example 2:</p> <pre><code>return codecs.charmap_encode(input,errors,encoding_table) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position(...) </code></pre> <p>catching the 2nd example is obvious:</p> <pre><code>try: ... except UnicodeDecodeError: ... </code></pre> <p>how do i catch specifically the first error?</p>
5
2009-07-15T11:04:53Z
1,130,786
<p>When you have an exception that unique to a module you simply have to use the same class used to raise it. Here you have the advantage because you already know where the exception class is because you're raising it.</p> <pre><code>try: raise socket.error, msg except socket.error, (value, message): # O no! </code></pre> <p>But for other such exception you either have to wait until it gets thrown to find where the class is, or you have to read through the documentation to find out where it is coming from.</p>
0
2009-07-15T11:10:47Z
[ "python", "exception" ]
which exception catches xxxx error in python
1,130,764
<p>given a traceback error log, i don't always know how to catch a particular exception.</p> <p>my question is in general, how do i determine which "except" clause to write in order to handle a certain exception.</p> <p>example 1:</p> <pre><code> File "c:\programs\python\lib\httplib.py", line 683, in connect raise socket.error, msg error: (10065, 'No route to host') </code></pre> <p>example 2:</p> <pre><code>return codecs.charmap_encode(input,errors,encoding_table) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position(...) </code></pre> <p>catching the 2nd example is obvious:</p> <pre><code>try: ... except UnicodeDecodeError: ... </code></pre> <p>how do i catch specifically the first error?</p>
5
2009-07-15T11:04:53Z
1,130,795
<p>First one is also obvious, as second one e.g.</p> <pre><code>&gt;&gt;&gt; try: ... socket.socket().connect(("0.0.0.0", 0)) ... except socket.error: ... print "socket error!!!" ... socket error!!! &gt;&gt;&gt; </code></pre>
2
2009-07-15T11:11:42Z
[ "python", "exception" ]
How to create arrayType for WSDL in Python (using suds)?
1,130,819
<p><strong>Environment:</strong></p> <ul> <li>Python v2.6.2</li> <li>suds v0.3.7</li> </ul> <p>The WSDL (server) I work with, have the following schema sub-sections (I tried to write it clearly using plain text) -</p> <hr> <p><em><strong>[ sub-section #1 ]</em></strong></p> <pre><code>searchRequest: (searchRequest){ userIdentification = (userIdentification){ username = "" password = "" } itineraryArr = (itineraryArray){ _arrayType = "" _offset = "" _id = "" _href = "" _arrayType = "" } ... ... </code></pre> <hr> <p><em><strong>[ sub-section #2 ]</em></strong></p> <pre><code>itinerary: (itinerary){ departurePoint = (locationPoint){ locationId = None radius = None } arrivalPoint = (locationPoint){ locationId = None radius = None } ... ... </code></pre> <hr> <p>There is no problem with 'userIdentification' (which is a "simple" type)</p> <p>But, 'itineraryArr' is an array of 'itinerary', and I don't know how to use python to create XML array.</p> <p>I tried few combinations, for example</p> <pre><code>itinerary0 = self.client.factory.create('itinerary') itineraryArray = self.client.factory.create('itineraryArray') itineraryArray = [itinerary0] searchRequest.itineraryArr = itineraryArray </code></pre> <p>But all my trials resulted with the same server error -</p> <pre><code> Server raised fault: 'Cannot use object of type itinerary as array' (Fault){ faultcode = "SOAP-ENV:Server" faultstring = "Cannot use object of type itinerary as array" } </code></pre>
6
2009-07-15T11:20:23Z
1,139,372
<p>I believe what you are looking for is:</p> <pre><code>itinerary0 = self.client.factory.create('itinerary') itineraryArray = self.client.factory.create('itineraryArray') print itineraryArray itineraryArray.itinerary.append(itinerary0) </code></pre> <p>Just had to do this myself;) What helped me find it was printing to the console. That would have probably given you the following:</p> <pre><code> (itineraryArray){ itinerary[] = &lt;empty&gt; } </code></pre> <p>Cheers,Jacques</p>
3
2009-07-16T18:21:35Z
[ "python", "xml", "arrays", "wsdl", "suds" ]
How to create arrayType for WSDL in Python (using suds)?
1,130,819
<p><strong>Environment:</strong></p> <ul> <li>Python v2.6.2</li> <li>suds v0.3.7</li> </ul> <p>The WSDL (server) I work with, have the following schema sub-sections (I tried to write it clearly using plain text) -</p> <hr> <p><em><strong>[ sub-section #1 ]</em></strong></p> <pre><code>searchRequest: (searchRequest){ userIdentification = (userIdentification){ username = "" password = "" } itineraryArr = (itineraryArray){ _arrayType = "" _offset = "" _id = "" _href = "" _arrayType = "" } ... ... </code></pre> <hr> <p><em><strong>[ sub-section #2 ]</em></strong></p> <pre><code>itinerary: (itinerary){ departurePoint = (locationPoint){ locationId = None radius = None } arrivalPoint = (locationPoint){ locationId = None radius = None } ... ... </code></pre> <hr> <p>There is no problem with 'userIdentification' (which is a "simple" type)</p> <p>But, 'itineraryArr' is an array of 'itinerary', and I don't know how to use python to create XML array.</p> <p>I tried few combinations, for example</p> <pre><code>itinerary0 = self.client.factory.create('itinerary') itineraryArray = self.client.factory.create('itineraryArray') itineraryArray = [itinerary0] searchRequest.itineraryArr = itineraryArray </code></pre> <p>But all my trials resulted with the same server error -</p> <pre><code> Server raised fault: 'Cannot use object of type itinerary as array' (Fault){ faultcode = "SOAP-ENV:Server" faultstring = "Cannot use object of type itinerary as array" } </code></pre>
6
2009-07-15T11:20:23Z
2,123,324
<p>For this type of structure I set an attribute called 'item' on the array object and then append the list member to it. Something like:</p> <pre><code>itineraryArray = self.client.factory.create('itineraryArray') itineraryArray.item = [itinerary0] </code></pre> <p>Which parses and passes in fine, even for complex calls with multiple levels.</p>
2
2010-01-23T13:45:41Z
[ "python", "xml", "arrays", "wsdl", "suds" ]
How to create arrayType for WSDL in Python (using suds)?
1,130,819
<p><strong>Environment:</strong></p> <ul> <li>Python v2.6.2</li> <li>suds v0.3.7</li> </ul> <p>The WSDL (server) I work with, have the following schema sub-sections (I tried to write it clearly using plain text) -</p> <hr> <p><em><strong>[ sub-section #1 ]</em></strong></p> <pre><code>searchRequest: (searchRequest){ userIdentification = (userIdentification){ username = "" password = "" } itineraryArr = (itineraryArray){ _arrayType = "" _offset = "" _id = "" _href = "" _arrayType = "" } ... ... </code></pre> <hr> <p><em><strong>[ sub-section #2 ]</em></strong></p> <pre><code>itinerary: (itinerary){ departurePoint = (locationPoint){ locationId = None radius = None } arrivalPoint = (locationPoint){ locationId = None radius = None } ... ... </code></pre> <hr> <p>There is no problem with 'userIdentification' (which is a "simple" type)</p> <p>But, 'itineraryArr' is an array of 'itinerary', and I don't know how to use python to create XML array.</p> <p>I tried few combinations, for example</p> <pre><code>itinerary0 = self.client.factory.create('itinerary') itineraryArray = self.client.factory.create('itineraryArray') itineraryArray = [itinerary0] searchRequest.itineraryArr = itineraryArray </code></pre> <p>But all my trials resulted with the same server error -</p> <pre><code> Server raised fault: 'Cannot use object of type itinerary as array' (Fault){ faultcode = "SOAP-ENV:Server" faultstring = "Cannot use object of type itinerary as array" } </code></pre>
6
2009-07-15T11:20:23Z
4,753,080
<p>I'm in the same case, with a RPC/encoded style WS and a method that contains a soap array. a print request (where <code>request = client.factory.create('Request')</code>) gives:</p> <pre><code>(Request){ requestid = None option = (ArrayOfOption){ _arrayType = "" _offset = "" _id = "" _href = "" _arrayType = "" } } </code></pre> <p>The solution given by Jacques (1request.option.append(option1)1) does not work, as it ends with an error message <code>ArrayOfOption instance has no attribute append</code>.</p> <p>The solution given by mcauth looks like this:</p> <pre><code>array = client.factory.create('ArrayOfOption') array.item = [option1, option2, option3, option4, option5, option6] request.option=array </code></pre> <p>It works so so, as the resulting SOAP message shows no <code>arrayType</code> attribute:</p> <pre><code>&lt;option xsi:type="ns3:ArrayOfOption"&gt; </code></pre> <p>The best solution I found is also the simplest:</p> <pre><code>request.option = [option1, option2, option3, option4, option5, option6] </code></pre> <p>It ends with a good SOAP message:</p> <pre><code>&lt;option xsi:type="ns0:ArrayOfOption" ns3:arrayType="ns0:Option[6]"&gt; </code></pre> <p>as expected by the server side WS.</p>
5
2011-01-20T21:55:53Z
[ "python", "xml", "arrays", "wsdl", "suds" ]
Following a javascript postback using COM + IE automation to save text file
1,130,857
<p>I want to automate the archiving of the data on this page <a href="http://energywatch.natgrid.co.uk/EDP-PublicUI/Public/InstantaneousFlowsIntoNTS.aspx" rel="nofollow">http://energywatch.natgrid.co.uk/EDP-PublicUI/Public/InstantaneousFlowsIntoNTS.aspx</a>, and upload into a database. </p> <p>I have been using python and win32com (behind a corporate proxy, so no direct net access, hence I am using IE to do so) on other pages to do this. My question is that is there anyway to extract and save the CSV data that is returned when clicking the "Click here to download data" link at the bottom? This link is a javascript postback, and would be much easier than reformatting the page itself into CSV.</p> <p>. Of course, I'm not necessarily committed to using Python if a simpler alternative can be suggested?</p> <p>Thanks</p>
1
2009-07-15T11:27:48Z
1,131,150
<p>Here's a better way, using the <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> library.</p> <pre><code> import mechanize b = mechanize.Browser() b.set_proxies({'http': 'yourproxy.corporation.com:3128' }) b.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')] b.open("http://energywatch.natgrid.co.uk/EDP-PublicUI/Public/InstantaneousFlowsIntoNTS.aspx") b.select_form(name="form1") b.form.find_control(name='__EVENTTARGET').readonly = False b.form['__EVENTTARGET'] = 'a1' print b.submit().read() </code></pre> <p>Note how you can specify that mechanize should use a proxy server (also possible using plain <code>urllib</code>). Also note how ASP.NETs javascript postback is simulated.</p> <p><strong>Edit:</strong></p> <p>If your proxy server is using NTLM authentication, that could be the problem. AFAIK urllib2 does not handle NTLM authentication. You could try the <a href="http://ntlmaps.sourceforge.net/" rel="nofollow">NTLM Authorization Proxy Server</a>. From the <a href="http://ntlmaps.sourceforge.net/readme.txt" rel="nofollow">readme file</a>:</p> <p><hr /></p> <p>WHAT IS 'NTLM Authorization Proxy Server'?</p> <p>'NTLM Authorization Proxy Server' is a proxy-like software, that will authorize you at MS proxy server and at web servers (ISS especially) using MS proprietary NTLM authorization method and it can change some values in your client's request header so that those requests will look like ones made by MS IE. It is written in Python language. See www.python.org.</p> <p><hr /></p>
1
2009-07-15T12:38:01Z
[ "javascript", "python", "com", "website", "webpage" ]
most efficient data structure for a read-only list of strings (about 100,000) with fast prefix search
1,130,992
<p>I'm writing an application that needs to read a list of strings from a file, save them in a data structure, and then look up those strings by prefixes. The list of strings is simply a list of words in a given language. For example, if the search function gets "stup" as a parameter, it should return ["stupid", "stupidity", "stupor"...]. It should do so in O(log(n)*m) time, where n is the size of the data structure and m is the number of results and should be as fast as possible. Memory consumption is not a big issue right now. I'm writing this in python, so it would be great if you could point me to a suitable data structure (preferably) implemented in c with python wrappers. </p>
6
2009-07-15T12:04:42Z
1,131,014
<p>You want a trie.</p> <p><a href="http://en.wikipedia.org/wiki/Trie">http://en.wikipedia.org/wiki/Trie</a></p> <p>I've used them in Scrabble and Boggle programs. They're perfect for the use case you described (fast prefix lookup).</p> <p>Here's some sample code for building up a trie in Python. This is from a Boggle program I whipped together a few months ago. The rest is left as an exercise to the reader. But for prefix checking you basically need a method that starts at the root node (the variable <code>words</code>), follows the letters of the prefix to successive child nodes, and returns True if such a path is found and False otherwise.</p> <pre><code>class Node(object): def __init__(self, letter='', final=False): self.letter = letter self.final = final self.children = {} def __contains__(self, letter): return letter in self.children def get(self, letter): return self.children[letter] def add(self, letters, n=-1, index=0): if n &lt; 0: n = len(letters) if index &gt;= n: return letter = letters[index] if letter in self.children: child = self.children[letter] else: child = Node(letter, index==n-1) self.children[letter] = child child.add(letters, n, index+1) def load_dictionary(path): result = Node() for line in open(path, 'r'): word = line.strip().lower() result.add(word) return result words = load_dictionary('dictionary.txt') </code></pre>
15
2009-07-15T12:09:40Z
[ "python", "data-structures", "dictionary", "lookup" ]
most efficient data structure for a read-only list of strings (about 100,000) with fast prefix search
1,130,992
<p>I'm writing an application that needs to read a list of strings from a file, save them in a data structure, and then look up those strings by prefixes. The list of strings is simply a list of words in a given language. For example, if the search function gets "stup" as a parameter, it should return ["stupid", "stupidity", "stupor"...]. It should do so in O(log(n)*m) time, where n is the size of the data structure and m is the number of results and should be as fast as possible. Memory consumption is not a big issue right now. I'm writing this in python, so it would be great if you could point me to a suitable data structure (preferably) implemented in c with python wrappers. </p>
6
2009-07-15T12:04:42Z
1,131,016
<p>A <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow" title="Tries">trie (or prefix tree)</a> sounds right up your alley. It can do the search on a prefix string of length m in O(m) I believe.</p>
2
2009-07-15T12:10:52Z
[ "python", "data-structures", "dictionary", "lookup" ]
most efficient data structure for a read-only list of strings (about 100,000) with fast prefix search
1,130,992
<p>I'm writing an application that needs to read a list of strings from a file, save them in a data structure, and then look up those strings by prefixes. The list of strings is simply a list of words in a given language. For example, if the search function gets "stup" as a parameter, it should return ["stupid", "stupidity", "stupor"...]. It should do so in O(log(n)*m) time, where n is the size of the data structure and m is the number of results and should be as fast as possible. Memory consumption is not a big issue right now. I'm writing this in python, so it would be great if you could point me to a suitable data structure (preferably) implemented in c with python wrappers. </p>
6
2009-07-15T12:04:42Z
1,131,017
<p>string array.</p> <p>then binary search through it to search the first match then step one by one through it for all subsequent matches</p> <p>(i originally had linked list here too... but of course this doesn't have random access so this was 'bs' (which probably explains why I was downvoted). My binary search algorithm still is the fastest way to go though</p>
-2
2009-07-15T12:11:01Z
[ "python", "data-structures", "dictionary", "lookup" ]
most efficient data structure for a read-only list of strings (about 100,000) with fast prefix search
1,130,992
<p>I'm writing an application that needs to read a list of strings from a file, save them in a data structure, and then look up those strings by prefixes. The list of strings is simply a list of words in a given language. For example, if the search function gets "stup" as a parameter, it should return ["stupid", "stupidity", "stupor"...]. It should do so in O(log(n)*m) time, where n is the size of the data structure and m is the number of results and should be as fast as possible. Memory consumption is not a big issue right now. I'm writing this in python, so it would be great if you could point me to a suitable data structure (preferably) implemented in c with python wrappers. </p>
6
2009-07-15T12:04:42Z
1,131,035
<p>Some Python implementations of <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">tries</a>:</p> <ul> <li><a href="http://jtauber.com/2005/02/trie.py" rel="nofollow">http://jtauber.com/2005/02/trie.py</a></li> <li><a href="http://www.koders.com/python/fid7B6BC1651A9E8BBA547552FE3F039479A4DECC45.aspx" rel="nofollow">http://www.koders.com/python/fid7B6BC1651A9E8BBA547552FE3F039479A4DECC45.aspx</a></li> <li><a href="http://filoxus.blogspot.com/2007/11/trie-in-python.html" rel="nofollow">http://filoxus.blogspot.com/2007/11/trie-in-python.html</a></li> </ul>
4
2009-07-15T12:13:44Z
[ "python", "data-structures", "dictionary", "lookup" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
1,131,230
<p>u can't get it's md5 without read full content. but u can use <a href="http://docs.python.org/library/hashlib.html#hashlib.hash.update" rel="nofollow">update</a> function to read the files content block by block.<br /> m.update(a); m.update(b) is equivalent to m.update(a+b)</p>
1
2009-07-15T12:54:22Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
1,131,238
<p>Break the file into 128-byte chunks and feed them to MD5 consecutively using <code>update()</code>.</p> <p>This takes advantage of the fact that MD5 has 128-byte digest blocks. Basically, when MD5 <code>digest()</code>s the file, this is exactly what it is doing.</p> <p>If you make sure you free the memory on each iteration (i.e. not read the entire file to memory), this shall take no more than 128 bytes of memory.</p> <p>One example is to read the chunks like so:</p> <pre><code>f = open(fileName) while not endOfFile: f.read(128) </code></pre>
130
2009-07-15T12:55:07Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
1,131,255
<p>You need to read the file in chunks of suitable size:</p> <pre><code>def md5_for_file(f, block_size=2**20): md5 = hashlib.md5() while True: data = f.read(block_size) if not data: break md5.update(data) return md5.digest() </code></pre> <p>NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.</p> <p>So to do the whole lot in one method - use something like: </p> <pre><code>def generate_file_md5(rootdir, filename, blocksize=2**20): m = hashlib.md5() with open( os.path.join(rootdir, filename) , "rb" ) as f: while True: buf = f.read(blocksize) if not buf: break m.update( buf ) return m.hexdigest() </code></pre> <p>The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation</p> <p>I cross-checked the results using the 'jacksum' tool.</p> <pre><code>jacksum -a md5 &lt;filename&gt; </code></pre> <p><a href="http://www.jonelo.de/java/jacksum/">http://www.jonelo.de/java/jacksum/</a></p>
188
2009-07-15T12:59:25Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
4,213,255
<p>if you care about more pythonic (no 'while True') way of reading the file check this code:</p> <pre><code>import hashlib def checksum_md5(filename): md5 = hashlib.md5() with open(filename,'rb') as f: for chunk in iter(lambda: f.read(8192), b''): md5.update(chunk) return md5.digest() </code></pre> <p>Note that the iter() func needs an empty byte string for the returned iterator to halt at EOF, since read() returns b'' (not just '').</p>
90
2010-11-18T09:24:09Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
11,143,944
<p>Here's my version of @Piotr Czapla's method:</p> <pre><code>def md5sum(filename): md5 = hashlib.md5() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(128 * md5.block_size), b''): md5.update(chunk) return md5.hexdigest() </code></pre>
45
2012-06-21T17:54:23Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
17,782,753
<p>Using multiple comment/answers in this thread, here is my solution :</p> <pre><code>import hashlib def md5_for_file(path, block_size=256*128, hr=False): ''' Block size directly depends on the block size of your filesystem to avoid performances issues Here I have blocks of 4096 octets (Default NTFS) ''' md5 = hashlib.md5() with open(path,'rb') as f: for chunk in iter(lambda: f.read(block_size), b''): md5.update(chunk) if hr: return md5.hexdigest() return md5.digest() </code></pre> <ul> <li>This is "pythonic"</li> <li>This is a function</li> <li>It avoids implicit values: always prefer explicit ones.</li> <li>It allows (very important) performances optimizations</li> </ul> <p>And finally,</p> <p><strong>- This has been built by a community, thanks all for your advices/ideas.</strong></p>
24
2013-07-22T08:14:48Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
29,446,602
<p>I'm not sure that there isn't a bit too much fussing around here. I recently had problems with md5 and files stored as blobs on MySQL so I experimented with various file sizes and the straightforward Python approach, viz:</p> <pre><code>FileHash=hashlib.md5(FileData).hexdigest() </code></pre> <p>I could detect no noticeable performance difference with a range of file sizes 2Kb to 20Mb and therefore no need to 'chunk' the hashing. Anyway, if Linux has to go to disk, it will probably do it at least as well as the average programmer's ability to keep it from doing so. As it happened, the problem was nothing to do with md5. If you're using MySQL, don't forget the md5() and sha1() functions already there.</p>
-3
2015-04-04T12:50:09Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
31,278,890
<p><strong>A remix of Bastien Semene code that take Hawkwing comment about generic hashing function into consideration...</strong></p> <pre><code>def hash_for_file(path, algorithm=hashlib.algorithms[0], block_size=256*128, human_readable=True): """ Block size directly depends on the block size of your filesystem to avoid performances issues Here I have blocks of 4096 octets (Default NTFS) Linux Ext4 block size sudo tune2fs -l /dev/sda5 | grep -i 'block size' &gt; Block size: 4096 Input: path: a path algorithm: an algorithm in hashlib.algorithms ATM: ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') block_size: a multiple of 128 corresponding to the block size of your filesystem human_readable: switch between digest() or hexdigest() output, default hexdigest() Output: hash """ if algorithm not in hashlib.algorithms: raise NameError('The algorithm "{algorithm}" you specified is ' 'not a member of "hashlib.algorithms"'.format(algorithm=algorithm)) hash_algo = hashlib.new(algorithm) # According to hashlib documentation using new() # will be slower then calling using named # constructors, ex.: hashlib.md5() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(block_size), b''): hash_algo.update(chunk) if human_readable: file_hash = hash_algo.hexdigest() else: file_hash = hash_algo.digest() return file_hash </code></pre>
3
2015-07-07T20:43:07Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
38,426,184
<pre><code>import hashlib,re opened = open('/home/parrot/pass.txt','r') opened = open.readlines() for i in opened: strip1 = i.strip('\n') hash_object = hashlib.md5(strip1.encode()) hash2 = hash_object.hexdigest() print hash2 </code></pre>
0
2016-07-17T21:37:53Z
[ "python", "md5", "hashlib" ]
Get MD5 hash of big files in Python
1,131,220
<p>I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in <a href="https://docs.python.org/2/library/hashlib.html"><code>hashlib.md5()</code></a> function.</p> <p>The problem is with very big files that their sizes could exceed RAM size.</p> <p>How to get the MD5 hash of a file without loading the whole file to memory?</p>
156
2009-07-15T12:52:07Z
38,719,060
<p>Implementation of accepted answer for Django:</p> <pre><code>import hashlib from django.db import models class MyModel(models.Model): file = models.FileField() # any field based on django.core.files.File def get_hash(self): hash = hashlib.md5() for chunk in self.file.chunks(chunk_size=8192): hash.update(chunk) return hash.hexdigest() </code></pre>
0
2016-08-02T11:22:09Z
[ "python", "md5", "hashlib" ]
Form validation in django
1,131,232
<p>I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? </p>
8
2009-07-15T12:54:46Z
1,131,248
<p>You should ALWAYS validate your form on the server side, client side validation is but a convenience for the user only.</p> <p>That being said, Django forms has a variable form.errors which shows if certain form fields were incorrect.</p> <p>{{ form.name_of_field.errors }} can give you each individual error of each field that's incorrectly filled out. See more here:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/">http://docs.djangoproject.com/en/dev/topics/forms/</a></p>
15
2009-07-15T12:58:10Z
[ "python", "django", "django-forms" ]
Form validation in django
1,131,232
<p>I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? </p>
8
2009-07-15T12:54:46Z
1,131,590
<p>There's a pluggable Django app (<a href="http://code.google.com/p/django-ajax-forms/">django-ajax-forms</a>) that helps validate forms on the client side through JavaScript. But as AlbertoPL says, use client side validation only as a usability measure (e.g. telling a user that his desired username is already taken without reloading the registration page). There are all kind of ways to sidestep client side validation, in most cases as simple as deactivating JavaScript. </p> <p>Generally speaking: presume all data coming from the outside as faulty until validated.</p>
5
2009-07-15T13:59:04Z
[ "python", "django", "django-forms" ]
Form validation in django
1,131,232
<p>I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? </p>
8
2009-07-15T12:54:46Z
10,529,371
<p>Just came accross django-floppyforms, which seems to do clientside validation by default. They use HTML5 which supports clientside validation by default. Not sure if they also use javascript though if the browser doesn't support HTML5. Haven't tried it myself yet.</p> <p>Link to django-floppyforms: <a href="http://django-floppyforms.readthedocs.org/en/latest/differences.html" rel="nofollow" title="Documentation">Documentation</a> and <a href="https://github.com/brutasse/django-floppyforms" rel="nofollow" title="Github Sourcecode">Github</a></p>
4
2012-05-10T07:34:38Z
[ "python", "django", "django-forms" ]
Form validation in django
1,131,232
<p>I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? </p>
8
2009-07-15T12:54:46Z
14,750,452
<p>You will need to do this is JS. <a href="http://agiliq.com/blog/2013/02/easy-client-side-form-validations-for-django-djang/" rel="nofollow">This app</a> integrates forms with parsley.js to tag the forms with correct data-* attributes automatically.</p>
0
2013-02-07T11:50:48Z
[ "python", "django", "django-forms" ]
Form validation in django
1,131,232
<p>I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? </p>
8
2009-07-15T12:54:46Z
29,097,358
<p>If you are using bootstrap then you can simply add required attribute in forms field. For example if there is programe field then you can validate it like:</p> <p>In forms.py:</p> <pre><code>programme = forms.ChoiceField(course_choices,required=True, widget=forms.Select(attrs={'required':'required'})) </code></pre> <p>Note: It requires to link to bootstrap files in your <code>.html</code> page of that form.</p>
2
2015-03-17T10:59:01Z
[ "python", "django", "django-forms" ]
server side marker clustering in django
1,131,400
<p>I am creating a mashup in django and google maps and I am wondering if there is a way of clustering markers on the server side using django/python. </p>
0
2009-07-15T13:27:54Z
1,132,754
<p>I came up with the code below to figure out if one marker is close enough to another for clustering - close if two cluster icons start overlapping. Works for the whole world map for all zoom levels.</p> <p>The problem is that map projection is non-linear and you can't just set some <code>delta_lang</code> <code>delta_lat</code> tolerance - both will depend on the lattitude. For local maps it is not a problem though.</p> <p>If you want to do all on the server side you will have to calculate clustered markers for each zoomlelvel either per AJAX call or print them all at once.</p> <pre><code>function isCloseTo($other,$z){//$z is zoomlevel $delta_lat = abs($this-&gt;lattitude - $other-&gt;lattitude); $delta_lng = abs($this-&gt;longitude - $other-&gt;longitude); $l = abs($this-&gt;lattitude); $l2 = $l*$l; $l3 = $l2*$l; $l4 = $l3*$l; $factor = 1 +0.0000312*$l +0.0003604*$l2 -0.000009858*$l3 +0.0000001506*$l4; $tol_lat = (45.42*exp(-0.6894339*$z)/3)/$factor; $tol_lng = 21.845*exp(-0.67686*$z)/2; if ($delta_lat &lt; $tol_lat and $delta_lng &lt; $tol_lng){ return true; } else{ return false; } } </code></pre>
0
2009-07-15T17:23:06Z
[ "python", "django", "google-maps" ]
server side marker clustering in django
1,131,400
<p>I am creating a mashup in django and google maps and I am wondering if there is a way of clustering markers on the server side using django/python. </p>
0
2009-07-15T13:27:54Z
1,617,001
<p>I have implemented server side clustering in Django on my real estate/rentals site; I explain it <a href="http://forum.mapaplace.com/discussion/3/server-side-marker-clustering-python-source-code/" rel="nofollow">here</a>.</p>
1
2009-10-24T04:54:59Z
[ "python", "django", "google-maps" ]
Are Generators Threadsafe?
1,131,430
<p>I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.</p> <p>Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multiple threads? </p> <p>If not, is there a better way to approach the problem? I need something that will cycle through a list and produce the next value for whichever thread calls it.</p>
26
2009-07-15T13:32:05Z
1,131,458
<p>It's not thread-safe; simultaneous calls may interleave, and mess with the local variables.</p> <p>The common approach is to use the master-slave pattern (now called farmer-worker pattern in PC). Make a third thread which generates data, and add a Queue between the master and the slaves, where slaves will read from the queue, and the master will write to it. The standard queue module provides the necessary thread safety and arranges to block the master until the slaves are ready to read more data.</p>
40
2009-07-15T13:37:59Z
[ "python", "multithreading", "thread-safety", "generator" ]
Are Generators Threadsafe?
1,131,430
<p>I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.</p> <p>Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multiple threads? </p> <p>If not, is there a better way to approach the problem? I need something that will cycle through a list and produce the next value for whichever thread calls it.</p>
26
2009-07-15T13:32:05Z
1,131,483
<p>No, they are not thread-safe. You can find interesting info about generators and multi-threading in:</p> <p><strong><a href="http://www.dabeaz.com/generators/Generators.pdf">http://www.dabeaz.com/generators/Generators.pdf</a></strong></p>
5
2009-07-15T13:44:10Z
[ "python", "multithreading", "thread-safety", "generator" ]
Are Generators Threadsafe?
1,131,430
<p>I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.</p> <p>Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multiple threads? </p> <p>If not, is there a better way to approach the problem? I need something that will cycle through a list and produce the next value for whichever thread calls it.</p>
26
2009-07-15T13:32:05Z
1,132,297
<p>It depends on which python implementation you're using. In CPython, the GIL makes all operations on python objects threadsafe, as only one thread can be executing code at any given time.</p> <p><a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">http://en.wikipedia.org/wiki/Global_Interpreter_Lock</a></p>
-7
2009-07-15T15:54:56Z
[ "python", "multithreading", "thread-safety", "generator" ]
Are Generators Threadsafe?
1,131,430
<p>I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.</p> <p>Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multiple threads? </p> <p>If not, is there a better way to approach the problem? I need something that will cycle through a list and produce the next value for whichever thread calls it.</p>
26
2009-07-15T13:32:05Z
1,133,605
<p>Edited to add benchmark below.</p> <p>You can wrap a generator with a lock. For example,</p> <pre><code>import threading class LockedIterator(object): def __init__(self, it): self.lock = threading.Lock() self.it = it.__iter__() def __iter__(self): return self def next(self): self.lock.acquire() try: return self.it.next() finally: self.lock.release() gen = [x*2 for x in [1,2,3,4]] g2 = LockedIterator(gen) print list(g2) </code></pre> <p><hr /></p> <p>Locking takes 50ms on my system, Queue takes 350ms. Queue is useful when you really do have a queue; for example, if you have incoming HTTP requests and you want to queue them for processing by worker threads. (That doesn't fit in the Python iterator model--once an iterator runs out of items, it's done.) If you really do have an iterator, then LockedIterator is a faster and simpler way to make it thread safe.</p> <pre><code>from datetime import datetime import threading num_worker_threads = 4 class LockedIterator(object): def __init__(self, it): self.lock = threading.Lock() self.it = it.__iter__() def __iter__(self): return self def next(self): self.lock.acquire() try: return self.it.next() finally: self.lock.release() def test_locked(it): it = LockedIterator(it) def worker(): try: for i in it: pass except Exception, e: print e raise threads = [] for i in range(num_worker_threads): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join() def test_queue(it): from Queue import Queue def worker(): try: while True: item = q.get() q.task_done() except Exception, e: print e raise q = Queue() for i in range(num_worker_threads): t = threading.Thread(target=worker) t.setDaemon(True) t.start() t1 = datetime.now() for item in it: q.put(item) q.join() start_time = datetime.now() it = [x*2 for x in range(1,10000)] test_locked(it) #test_queue(it) end_time = datetime.now() took = end_time-start_time print "took %.01f" % ((took.seconds + took.microseconds/1000000.0)*1000) </code></pre>
33
2009-07-15T19:55:32Z
[ "python", "multithreading", "thread-safety", "generator" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,633
<p>Very simple solution: Use composition rather than inheritance. Rather than having Student inherit from Contact and Billing, make Contact a field/attribute of Person and inherit from that. Make Billing a field of Student. Make Parent a self-reference field of Person. </p>
2
2009-07-15T14:08:30Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,636
<p>It doesn't sound like you really need multiple inheritance. In fact, you don't ever really <em>need</em> multiple inheritance. It's just a question of whether multiple inheritance simplifies things (which I couldn't see as being the case here).</p> <p>I would create a Person class that has all the code that the adult and student would share. Then, you can have an Adult class that has all of the things that <em>only</em> the adult needs and a Child class that has the code <em>only</em> the child needs.</p>
2
2009-07-15T14:09:08Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,655
<p>What you have is an example of Role -- it's a common trap to model Role by inheritance, but Roles can change, and changing an object's inheritance structure (even in languages where it's possible, like Python) is not recommended. Children grow and become adults, and some adults will also be parents of children students as well as adult students themselves -- they might then drop either role but need to keep the other (their child changes schools but they don't, or viceversa).</p> <p>Just have a class Person with mandatory fields and optional ones, and the latter, representing Roles, can change. "Asking for a list" (quite independently of inheritance or otherwise) can be done either by building the list on the fly (walking through all objects to check for each whether it meets requirements) or maintaining lists corresponding to the possible requirements (or a mix of the two strategies for both frequent and ad-hoc queries). A database of some sort is likely to help here (and most DBs work much better without inheritance in the way;-).</p>
8
2009-07-15T14:12:30Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,670
<p>As I'm sure someone else will comment soon (if they haven't already), one good OO principle is "<a href="http://www.artima.com/lejava/articles/designprinciples4.html" rel="nofollow">Favor composition over inheritance</a>". From your description, it sounds suspiciously like you're breaking the <a href="http://en.wikipedia.org/wiki/Single%5Fresponsibility%5Fprinciple" rel="nofollow">Single Responsibility Principle</a>, and should be breaking down the functionality into separate objects.</p> <p>It also occurs to me that Python supports <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping" rel="nofollow">duck typing</a>, which begs the question "Why is it so important that all the classes have a common base class?"</p>
5
2009-07-15T14:14:50Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,714
<p>One solution is to create a base Info class/interface that the classes ContactInfo, StudentInfo, and BillingInfo inherit from. Have some sort of Person object that contains a list of Info objects, and then you can populate the list of Info objects with ContactInfo, StudentInfo, etc.</p>
0
2009-07-15T14:21:58Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,811
<p>This sounds like something that could be done quite nicely and flexibly with a component architecture, like zope.components. Components are in a way a sort of super-flexible composition patterns.</p> <p>In this case I'd probably end up doing something when you load the data to also set marker interfaces on it depending on some information, like if age >= 18 you set the IAdult interface, etc. You can then get the adult information by doing </p> <pre><code>adultschema = IAdultSchema(person) </code></pre> <p>or something like that. (Edit: Actually I'd probably use</p> <pre><code>queryAdapters(person, ISchema) </code></pre> <p>to get all schemas in one go. :)</p> <p>A component architecture <em>may</em> be overkill, but once you got used to thinking like that, many problems get trivial. :)</p> <p>Check out Brandons excellent PyCon talk about it: <a href="http://www.youtube.com/watch?v=UF77e2TeeQo" rel="nofollow">http://www.youtube.com/watch?v=UF77e2TeeQo</a> And my intro blog post: <a href="http://regebro.wordpress.com/2007/11/16/a-python-component-architecture/" rel="nofollow">http://regebro.wordpress.com/2007/11/16/a-python-component-architecture/</a></p>
1
2009-07-15T14:38:36Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,818
<p>I think your requirements are over-simplified, since in a real situation, you might have students with their own accounts to handle billing even if they are minors who need parent contact information. Also, you might have parental contact information be different from billing information in an actual situation. You might also have adult students with someone else to bill. BUT, that aside - looking at your requirements, here is one way:</p> <p>classes: Person, BillingInfo, StudentInfo.</p> <p>All people are instances of class Person...</p> <pre><code>class Person: # Will have contact fields all people have - or you could split these off into an # object. parent # Will be set to None for adults or else point to their parent's # Person object. billing_info # Set to None for non-adults, else to their BillingInfo object. student_info # Set to None for non-student parents, else to their StudentInfo # object. </code></pre> <p>Checking the fields will allow you to create lists as you desire.</p>
1
2009-07-15T14:39:31Z
[ "python", "oop", "multiple-inheritance" ]
Eliminating multiple inheritance
1,131,599
<p>I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.</p> <p>Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult students, in which case I need contact/student/billing info, or they can be children, in which case I need contact/student/parent info.</p> <p>Just to be clear on how the system will be used, I need to be able to ask for a list of all adults (and I will get adult students plus parents), or a list of all students (and I will get child students plus adult students).</p> <p>Also, all of these objects need to have a common base class.</p>
9
2009-07-15T14:01:24Z
1,131,847
<p>In pseudocode, you could do something like this:</p> <pre><code>Class Student Inherits WhateverBase Private m_StudentType as EnumStudentTypes 'an enum containing: Adult, Child Private m_Billing as Billing Private m_Contact as Contact Private m_Parent as Parent Public Sub Constructor(studentType, billing, contact, parent) ...logic to make sure we have the right combination depending on studentType. ...throw an exception if we try to assign a a parent to an adult, etc. ...maybe you could have seperate constructors, one for each studenttype. End Sub Public Property StudentType as EnumStudentTypes Get Return m_StudentType End Get End Sub Public Property Parent Get ...code to make sure we're using a studentType that has a parent, ...and throws an exception if not. Otherwise it returns m_Parent End Get End Sub [more properties] End Class Student </code></pre> <p>Then you could create a class called StudentManager:</p> <pre><code>Public Class StudentManager Public Function GetAdults(studentCollection(Of Students)) as StudentCollection(Of Students) Dim ResultCollection(Of Students) ...Loop through studentCollection, adding all students where Student.StudentType=Adult Return ResultCollection End Function [Other Functions] End Class Public Enum StudentType Adult=0 Child=1 End Enum </code></pre>
0
2009-07-15T14:44:17Z
[ "python", "oop", "multiple-inheritance" ]
Chain FormEncode Validators
1,131,926
<p><strong>Problem:</strong></p> <p>I have a form in TurboGears 2 that has a text field for a list of e-mails. Is there a simple way using ToscaWidgets or FormEncode to chain form validators for Set and Email or will I have to write my own validator for this?</p>
0
2009-07-15T14:56:31Z
1,133,358
<p>What I wanted was a validator I could just stick into a field like the String and Int validators. I found there was no way to do this unless I created my own validator. I'm posting it here for completeness sake, and so others can benefit.</p> <pre><code>from formencode import FancyValidator, Invalid from formencode.validators import Email class EmailList(FancyValidator): """ Takes a delimited (default is comma) string and returns a list of validated e-mails Set the delimiter by passing delimiter="A_DELIMITER" to the constructor. Also takes all arguments a FancyValidator does. The e-mails will always be stripped of whitespace. """ def _to_python(self, value, state): try: values = str(value).split(self.delimiter) except AttributeError: values = str(value).split(',') returnValues = [] emailValidator = Email() for value in values: returnValues.append( emailValidator._to_python(value.strip(), state) ) return values </code></pre>
0
2009-07-15T19:12:58Z
[ "python", "widget", "turbogears", "formencode", "toscawidgets" ]
Chain FormEncode Validators
1,131,926
<p><strong>Problem:</strong></p> <p>I have a form in TurboGears 2 that has a text field for a list of e-mails. Is there a simple way using ToscaWidgets or FormEncode to chain form validators for Set and Email or will I have to write my own validator for this?</p>
0
2009-07-15T14:56:31Z
1,134,567
<p>I think it should be more like the below. It has the advantage of trying each email instead of just stopping at the first invalid. It will also add the errors to the state so you could tell which ones had failed.</p> <pre><code>from formencode import FancyValidator, Invalid from formencode.validators import Email class EmailList(FancyValidator): """ Takes a delimited (default is comma) string and returns a list of validated e-mails Set the delimiter by passing delimiter="A_DELIMITER" to the constructor. Also takes all arguments a FancyValidator does. The e-mails will always be stripped of whitespace. """ def _to_python(self, value, state): try: values = str(value).split(self.delimiter) except AttributeError: values = str(value).split(',') validator = formencode.ForEach(validators.Email()) validator.to_python(values, state) return [value.strip() for value in values] </code></pre>
0
2009-07-15T23:00:11Z
[ "python", "widget", "turbogears", "formencode", "toscawidgets" ]
Chain FormEncode Validators
1,131,926
<p><strong>Problem:</strong></p> <p>I have a form in TurboGears 2 that has a text field for a list of e-mails. Is there a simple way using ToscaWidgets or FormEncode to chain form validators for Set and Email or will I have to write my own validator for this?</p>
0
2009-07-15T14:56:31Z
3,962,863
<p>from <a href="http://formencode.org/Validator.html" rel="nofollow">http://formencode.org/Validator.html</a></p> <p>Another notable validator is formencode.compound.All – this is a compound validator – that is, it’s a validator that takes validators as input. Schemas are one example; in this case All takes a list of validators and applies each of them in turn. formencode.compound.Any is its compliment, that uses the first passing validator in its list.</p>
1
2010-10-18T19:57:32Z
[ "python", "widget", "turbogears", "formencode", "toscawidgets" ]
Replacing Functionality of PIL (ImageDraw) in Google App Engine (GAE)
1,131,992
<p>So, Google App Engine doesn't look like it's going to include the Python Imaging Library <a href="http://code.google.com/p/googleappengine/issues/detail?id=38&amp;sort=-stars&amp;colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine/docs/python/images/">images api</a>, but it's paltry, and inadequate for what I need. </p> <p>I'm wondering what Python only (no C-extensions) there are that can replace the Image.paste and the ImageDraw modules. I don't want to write them myself, but that is an option. I'm also open to other solutions, such as "do the processing somewhere else, then call via api", if they're not <em>too</em> ugly. (For the record, the solution I just suggested seems <em>pretty ugly</em> to me.) </p> <p>How have others gotten around this? </p> <p>(I'm not wedded to GAE, just exploring, and this looks like a deal breaker for my app.) </p> <p>Notes:</p> <p>For me, crop, resize is not enough. In particular I need </p> <ol> <li>paste (replace part of an image with another.... can be faked with "compose")</li> <li>draw (for drawing gridlines, etc. Can be faked as well)</li> <li>text (write text on an image, much harder to fake, unless someone wants to correct me)</li> </ol>
5
2009-07-15T15:06:12Z
1,134,823
<p>My skimpygimpy.sourceforge.net will do drawing and text, but it won't edit existing images (but it could be modified for that, of course, if you want to dive in). It is pure python. see it working on google apps, for example at <a href="http://piopio.appspot.com/W1200_1400.stdMiddleware#Header51" rel="nofollow">http://piopio.appspot.com/W1200_1400.stdMiddleware#Header51</a>,</p> <p>That's an experimental site that I'll be messing with. The link may not work forever.</p>
2
2009-07-16T00:25:08Z
[ "python", "google-app-engine", "python-imaging-library" ]
Replacing Functionality of PIL (ImageDraw) in Google App Engine (GAE)
1,131,992
<p>So, Google App Engine doesn't look like it's going to include the Python Imaging Library <a href="http://code.google.com/p/googleappengine/issues/detail?id=38&amp;sort=-stars&amp;colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine/docs/python/images/">images api</a>, but it's paltry, and inadequate for what I need. </p> <p>I'm wondering what Python only (no C-extensions) there are that can replace the Image.paste and the ImageDraw modules. I don't want to write them myself, but that is an option. I'm also open to other solutions, such as "do the processing somewhere else, then call via api", if they're not <em>too</em> ugly. (For the record, the solution I just suggested seems <em>pretty ugly</em> to me.) </p> <p>How have others gotten around this? </p> <p>(I'm not wedded to GAE, just exploring, and this looks like a deal breaker for my app.) </p> <p>Notes:</p> <p>For me, crop, resize is not enough. In particular I need </p> <ol> <li>paste (replace part of an image with another.... can be faked with "compose")</li> <li>draw (for drawing gridlines, etc. Can be faked as well)</li> <li>text (write text on an image, much harder to fake, unless someone wants to correct me)</li> </ol>
5
2009-07-15T15:06:12Z
2,303,661
<p>I don't know if it has all features you want, but I have been messing with <a href="http://the.taoofmac.com/space/Projects/PNGCanvas" rel="nofollow">PNGCanvas</a>, and it does some things I have done before with PIL</p>
1
2010-02-20T20:47:45Z
[ "python", "google-app-engine", "python-imaging-library" ]
Replacing Functionality of PIL (ImageDraw) in Google App Engine (GAE)
1,131,992
<p>So, Google App Engine doesn't look like it's going to include the Python Imaging Library <a href="http://code.google.com/p/googleappengine/issues/detail?id=38&amp;sort=-stars&amp;colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine/docs/python/images/">images api</a>, but it's paltry, and inadequate for what I need. </p> <p>I'm wondering what Python only (no C-extensions) there are that can replace the Image.paste and the ImageDraw modules. I don't want to write them myself, but that is an option. I'm also open to other solutions, such as "do the processing somewhere else, then call via api", if they're not <em>too</em> ugly. (For the record, the solution I just suggested seems <em>pretty ugly</em> to me.) </p> <p>How have others gotten around this? </p> <p>(I'm not wedded to GAE, just exploring, and this looks like a deal breaker for my app.) </p> <p>Notes:</p> <p>For me, crop, resize is not enough. In particular I need </p> <ol> <li>paste (replace part of an image with another.... can be faked with "compose")</li> <li>draw (for drawing gridlines, etc. Can be faked as well)</li> <li>text (write text on an image, much harder to fake, unless someone wants to correct me)</li> </ol>
5
2009-07-15T15:06:12Z
11,319,510
<p>Now according to <a href="http://code.google.com/p/googleappengine/issues/detail?id=38&amp;sort=-stars&amp;colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary" rel="nofollow">this ticket</a> "On the Python 2.7 runtime, you can import PIL and use it directly. It's the real PIL, not a wrapper around the images API."</p>
1
2012-07-03T21:32:25Z
[ "python", "google-app-engine", "python-imaging-library" ]
Replacing Functionality of PIL (ImageDraw) in Google App Engine (GAE)
1,131,992
<p>So, Google App Engine doesn't look like it's going to include the Python Imaging Library <a href="http://code.google.com/p/googleappengine/issues/detail?id=38&amp;sort=-stars&amp;colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine/docs/python/images/">images api</a>, but it's paltry, and inadequate for what I need. </p> <p>I'm wondering what Python only (no C-extensions) there are that can replace the Image.paste and the ImageDraw modules. I don't want to write them myself, but that is an option. I'm also open to other solutions, such as "do the processing somewhere else, then call via api", if they're not <em>too</em> ugly. (For the record, the solution I just suggested seems <em>pretty ugly</em> to me.) </p> <p>How have others gotten around this? </p> <p>(I'm not wedded to GAE, just exploring, and this looks like a deal breaker for my app.) </p> <p>Notes:</p> <p>For me, crop, resize is not enough. In particular I need </p> <ol> <li>paste (replace part of an image with another.... can be faked with "compose")</li> <li>draw (for drawing gridlines, etc. Can be faked as well)</li> <li>text (write text on an image, much harder to fake, unless someone wants to correct me)</li> </ol>
5
2009-07-15T15:06:12Z
11,319,834
<p>Your assumption is wrong. If you use the Python 2.7 runtime, you can use PIL (version 1.1.7) as documented here: <a href="https://developers.google.com/appengine/docs/python/tools/libraries27" rel="nofollow">https://developers.google.com/appengine/docs/python/tools/libraries27</a>. This article also explains how to enable PIL for your app. </p> <p>BTW, the last comment in the bug you referenced also mentions it.</p>
2
2012-07-03T22:02:55Z
[ "python", "google-app-engine", "python-imaging-library" ]
Speeding up GTK tree view
1,132,512
<p>I'm writing an application for the Maemo platform using pygtk and the rendering speed of the tree view seems to be a problem. Since the application is a media controller I'm using transition animations in the UI. These animations slide the controls into view when moving around the UI. The issue with the tree control is that it is slow. </p> <p>Just moving the widget around in the middle of the screen is not that slow but if the cells are being exposed the framerate really drops. What makes this more annoying is that if the only area that is being exposed is the title row with the row labels, the framerate remains under control.</p> <p>Judging by this I'm suspecting the GTK tree view is drawing the full cells again each time a single row of pixels is being exposed. Is there a way to somehow force GTK to draw the whole widget into some buffer even if parts of it are off screen and then use the buffer to draw the widget when animating?</p> <p>Also is there a difference between using Viewport and scrolling that up and using Layout panel and moving the widgets down? I'd have imagined Viewport is faster but I saw no real difference when I tried both versions.</p> <p>I understand this isn't necessarily what GTK has been created for. Other alternative I've tried is pygame but I'd prefer some higher level implementaion that has widget based event handling built in. Also pygtk has the benefit of running in Windows and a window so development is easier.</p>
3
2009-07-15T16:34:10Z
1,134,480
<p>I never did this myself but you could try to implement the caching yourself. Instead of using the predefined cell renderers, implement your own cell renderer (possibly as a wrapper for the actual one), but cache the pixmaps.</p> <p>In PyGTK, you can use <a href="http://www.pygtk.org/docs/pygtk/class-pygtkgenericcellrenderer.html" rel="nofollow"><code>gtk.GenericCellRenderer</code></a>. In your decorator cell renderer, do the following when asked to render:</p> <ul> <li>keep a cache of off-screen pixmaps (or better, just one large one) and a cache of sizes</li> <li>if asked to predict the size or render, create a key from the relevant properties</li> <li>if the key exists in the cache, use the cached pixmap, blit the cached pixmap on the drawable you are given</li> <li>otherwise, first have the actual cell renderer do the work and then copy it</li> </ul> <p>The last step also implies that caching does incur an overhead during the first time the cell is renderered. This problem can be mitigated a bit by using a caching strategy. You might want to try out different things, based on the distribution of rendered values:</p> <ul> <li>if all cells are unique, not much to do than caching everything up to a certain limit, or some MRU strategy</li> <li>if you have some kind of <a href="http://en.wikipedia.org/wiki/Zipf%27s%5Flaw" rel="nofollow">Zipf distribution</a>, i.e. some cells are very common, while others are very rare, you should only cache the cells with high frequency and get rid off the caching overhead for rare cell values.</li> </ul> <p>That being said, I can't say if it's going to make any difference. My experience from a somewhat similar problem is that anything involving text is usually slow enough that caching makes sense---sorry that I can't give simpler advice.</p> <p>Before you try that, you could also simple write a decorating cell renderer which just counts how often your cells are actually rendered and get some timing information, so that you get an idea where the hot spots are and if caching the values would make any sense at all.</p>
1
2009-07-15T22:29:10Z
[ "python", "optimization", "gtk", "drawing", "pygtk" ]
Getting callable object from the frame
1,132,543
<p>Given the frame object (as returned by <a href="http://docs.python.org/library/sys.html#sys.%5Fgetframe" rel="nofollow">sys._getframe</a>, for instance), can I get the underlying callable object?</p> <p>Code explanation:</p> <pre><code>def foo(): frame = sys._getframe() x = some_magic(frame) # x is foo, now </code></pre> <p>Note that my problem is getting the object out of a frame, not the currently called object. </p> <p>Hope that's possible.</p> <p>Cheers,</p> <p>MH</p> <p><b>EDIT:</b></p> <p>I've somewhat managed to work around this problem. It was heavily inspired by Andreas' and Alexander's replies. Thanks guys for the time invested!</p> <pre><code>def magic(): fr = sys._getframe(1) for o in gc.get_objects(): if inspect.isfunction(o) and o.func_code is fr.f_code: return o class Foo(object): def bar(self): return magic() x = Foo().bar() assert x is Foo.bar.im_func</code></pre> <p>(works in 2.6.2, for py3k replace <code>func_code</code> with <code>__code__</code> and <code>im_func</code> with <code>__func__</code>)</p> <p>Then, I can aggressively traverse globals() or gc.get_objects() and dir() everything in search for the callable with the given function object. </p> <p>Feels a bit unpythonic for me, but works.</p> <p>Thanks, again!</p> <p>MH</p>
2
2009-07-15T16:41:39Z
1,132,625
<p>To support all cases, including the function being part of a class or just a global function, there is no straight-forward way of doing this. You might be able to get the complete call stack and iterate your way down through <code>globals()</code>, but it wouldn't be nice...</p> <p>The closest I can get you is this:</p> <pre><code>import sys, types def magic(): # Get the frame before the current one (i.e. frame of caller) frame = sys._getframe(1) # Default values and closure is lost here (because they belong to the # function object.) return types.FunctionType(frame.f_code, frame.f_globals) class MyClass(object): def foo(self, bar='Hello World!'): print bar return magic() test = MyClass() new_foo = test.foo() new_foo(test, 'Good Bye World!') </code></pre> <p>You'll be executing the exact same code, but it'll be in a new code wrapper (e.g., <code>FunctionType</code>.)</p> <p>I suspect you want to be able to restore the state of your application based on a stack... Here's something that will at least call the functions as similarly as possible to the original calls (the closure is still left out, because if you could get closures from the frames, getting the function that was called would be pretty easy):</p> <pre><code>import sys, types class MyClass(object): def __init__(self, temp): self.temp = temp def foo(self, bar): print self.temp, bar return sys._getframe() def test(hello): print hello, 'World!' return sys._getframe() def recall(frame): code = frame.f_code fn = types.FunctionType( code, frame.f_globals, code.co_name, # This is one BIG assumption that arguments are always last. tuple(frame.f_locals.values()[-code.co_argcount:])) return fn() test1 = MyClass('test1') frame1 = test1.foo('Hello World!') test2 = MyClass('test2') frame2 = test2.foo('Good Bye World!') frame3 = test2.foo('Sayonara!') frame4 = test('HI') print '-' recall(frame4) recall(frame3) recall(frame2) recall(frame1) </code></pre>
1
2009-07-15T16:59:35Z
[ "python" ]
Getting callable object from the frame
1,132,543
<p>Given the frame object (as returned by <a href="http://docs.python.org/library/sys.html#sys.%5Fgetframe" rel="nofollow">sys._getframe</a>, for instance), can I get the underlying callable object?</p> <p>Code explanation:</p> <pre><code>def foo(): frame = sys._getframe() x = some_magic(frame) # x is foo, now </code></pre> <p>Note that my problem is getting the object out of a frame, not the currently called object. </p> <p>Hope that's possible.</p> <p>Cheers,</p> <p>MH</p> <p><b>EDIT:</b></p> <p>I've somewhat managed to work around this problem. It was heavily inspired by Andreas' and Alexander's replies. Thanks guys for the time invested!</p> <pre><code>def magic(): fr = sys._getframe(1) for o in gc.get_objects(): if inspect.isfunction(o) and o.func_code is fr.f_code: return o class Foo(object): def bar(self): return magic() x = Foo().bar() assert x is Foo.bar.im_func</code></pre> <p>(works in 2.6.2, for py3k replace <code>func_code</code> with <code>__code__</code> and <code>im_func</code> with <code>__func__</code>)</p> <p>Then, I can aggressively traverse globals() or gc.get_objects() and dir() everything in search for the callable with the given function object. </p> <p>Feels a bit unpythonic for me, but works.</p> <p>Thanks, again!</p> <p>MH</p>
2
2009-07-15T16:41:39Z
1,132,768
<p>A little ugly but here it is:</p> <pre><code>frame.f_globals[frame.f_code.co_name] </code></pre> <p>Full example:</p> <pre><code>#!/usr/bin/env python import sys def foo(): frame = sys._getframe() x = frame.f_globals[frame.f_code.co_name] print foo is x foo() </code></pre> <p>Prints 'True'.</p>
1
2009-07-15T17:25:24Z
[ "python" ]
Getting callable object from the frame
1,132,543
<p>Given the frame object (as returned by <a href="http://docs.python.org/library/sys.html#sys.%5Fgetframe" rel="nofollow">sys._getframe</a>, for instance), can I get the underlying callable object?</p> <p>Code explanation:</p> <pre><code>def foo(): frame = sys._getframe() x = some_magic(frame) # x is foo, now </code></pre> <p>Note that my problem is getting the object out of a frame, not the currently called object. </p> <p>Hope that's possible.</p> <p>Cheers,</p> <p>MH</p> <p><b>EDIT:</b></p> <p>I've somewhat managed to work around this problem. It was heavily inspired by Andreas' and Alexander's replies. Thanks guys for the time invested!</p> <pre><code>def magic(): fr = sys._getframe(1) for o in gc.get_objects(): if inspect.isfunction(o) and o.func_code is fr.f_code: return o class Foo(object): def bar(self): return magic() x = Foo().bar() assert x is Foo.bar.im_func</code></pre> <p>(works in 2.6.2, for py3k replace <code>func_code</code> with <code>__code__</code> and <code>im_func</code> with <code>__func__</code>)</p> <p>Then, I can aggressively traverse globals() or gc.get_objects() and dir() everything in search for the callable with the given function object. </p> <p>Feels a bit unpythonic for me, but works.</p> <p>Thanks, again!</p> <p>MH</p>
2
2009-07-15T16:41:39Z
31,082,999
<p>Not really an answer, but a comment. I'd add it as a comment, but I don't have enough "reputation points".</p> <p>For what it's worth, here's a reasonable (I think) use case for wanting to do this sort of thing.</p> <p>My app uses gtk, and spins a lot of threads. As anyone whose done both of these at once knows, you can't touch the GUI outside the main thread. A typical workaround is to hand the callable that will touch the GUI to <code>idle_add()</code>, which will run it later, in the main thread, where it is safe. So I have a <em>lot</em> of occurrences of:</p> <pre><code>def threaded_gui_func(self, arg1, arg2): if threading.currentThread().name != 'MainThread': gobject.idle_add(self.threaded_gui_func, arg1, arg2) return # code that touches the GUI </code></pre> <p>It would be just a bit shorter and easier (and more conducive to cut-n-paste) if I could just do</p> <pre><code>def thread_gui_func(self, arg1, arg2): if idleIfNotMain(): return # code that touches the GUI </code></pre> <p>where idleIfNotMain() just returns False if we are in the main thread, but if not, it uses inspect (or whatever) to figure out the callable and args to hand off to <code>idle_add()</code>, then returns True. Getting the args I can figure out. Getting the callable appears not to be too easy. :-(</p>
0
2015-06-26T22:22:53Z
[ "python" ]
Must a secure cryptographic signature reside outside of the file it refers to?
1,132,766
<p>I'm programming a pet project in Python, and it involves users A &amp; B interacting over network, attempting to insure that each has a local copy of the same file from user C.</p> <p>The idea is that C gives each a file that has been digitally signed. A &amp; B trade the digital signatures they have, and check it out on their own copy. If the signature fails, then one of them has an incorrect/corrupt/modified version of the file.</p> <p>The question is, therefore, can C distribute a single file that somehow includes it's own signature? Or does C need to supply the file and signature separately?</p>
1
2009-07-15T17:25:12Z
1,132,787
<p>If you have control over the file format, yes. Include the signature in a header before the content proper, and make the signature cover only the content section of the file, <strong>not</strong> the entire file. Something like:</p> <pre><code>SIGNATURE=72ba51288199b829a4b9ca2ac911e60c BEGIN_CONTENTS ... real file contents here ... </code></pre>
4
2009-07-15T17:29:07Z
[ "python", "file", "cryptography", "digital-signature" ]
Must a secure cryptographic signature reside outside of the file it refers to?
1,132,766
<p>I'm programming a pet project in Python, and it involves users A &amp; B interacting over network, attempting to insure that each has a local copy of the same file from user C.</p> <p>The idea is that C gives each a file that has been digitally signed. A &amp; B trade the digital signatures they have, and check it out on their own copy. If the signature fails, then one of them has an incorrect/corrupt/modified version of the file.</p> <p>The question is, therefore, can C distribute a single file that somehow includes it's own signature? Or does C need to supply the file and signature separately?</p>
1
2009-07-15T17:25:12Z
1,132,796
<p>The digital signature from C alone should be enough for both A and B to confirm that their file is not corrupted, without ever communicating with eachother. If A and B did not receive a signature from C, they could each create a cryptographic hash of the file and compare the hash, but that does not require any digital signing on C's part.</p> <p>If you want C to sign the file, either send the signature and the file seperately, or wrap them both in some sort of container, such as a zip file or home grown solution (e.g., the first line in the file represents the signature, the rest is the payload).</p> <p>To answer your question literally, the signature doesn't have to be outside the file per se, but the part that is being signed cannot include the signature itself.</p>
5
2009-07-15T17:31:27Z
[ "python", "file", "cryptography", "digital-signature" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,133,013
<p>Suppose you have the following code</p> <pre><code>fruits = ("apples", "bananas", "loganberries") def eat(food=fruits): ... </code></pre> <p>When I see the declaration of eat, the least astonishing thing is to think that if the first parameter is not given, that it will be equal to the tuple <code>("apples", "bananas", "loganberries")</code></p> <p>However, supposed later on in the code, I do something like</p> <pre><code>def some_random_function(): global fruits fruits = ("blueberries", "mangos") </code></pre> <p>then if default parameters were bound at function execution rather than function declaration then I would be astonished (in a very bad way) to discover that fruits had been changed. This would be more astonishing IMO than discovering that your <code>foo</code> function above was mutating the list.</p> <p>The real problem lies with mutable variables, and all languages have this problem to some extent. Here's a question: suppose in Java I have the following code:</p> <pre><code>StringBuffer s = new StringBuffer("Hello World!"); Map&lt;StringBuffer,Integer&gt; counts = new HashMap&lt;StringBuffer,Integer&gt;(); counts.put(s, 5); s.append("!!!!"); System.out.println( counts.get(s) ); // does this work? </code></pre> <p>Now, does my map use the value of the <code>StringBuffer</code> key when it was placed into the map, or does it store the key by reference? Either way, someone is astonished; either the person who tried to get the object out of the <code>Map</code> using a value identical to the one they put it in with, or the person who can't seem to retrieve their object even though the key they're using is literally the same object that was used to put it into the map (this is actually why Python doesn't allow its mutable built-in data types to be used as dictionary keys).</p> <p>Your example is a good one of a case where Python newcomers will be surprised and bitten. But I'd argue that if we "fixed" this, then that would only create a different situation where they'd be bitten instead, and that one would be even less intuitive. Moreover, this is always the case when dealing with mutable variables; you always run into cases where someone could intuitively expect one or the opposite behavior depending on what code they're writing.</p> <p>I personally like Python's current approach: default function arguments are evaluated when the function is defined and that object is always the default. I suppose they could special-case using an empty list, but that kind of special casing would cause even more astonishment, not to mention be backwards incompatible.</p>
166
2009-07-15T18:11:26Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,133,255
<p>Well, the reason is quite simply that bindings are done when code is executed, and the function definition is executed, well... when the functions is defined.</p> <p>Compare this:</p> <pre><code>class BananaBunch: bananas = [] def addBanana(self, banana): self.bananas.append(banana) </code></pre> <p>This code suffers from the exact same unexpected happenstance. bananas is a class attribute, and hence, when you add things to it, it's added to all instances of that class. The reason is exactly the same.</p> <p>It's just "How It Works", and making it work differently in the function case would probably be complicated, and in the class case likely impossible, or at least slow down object instantiation a lot, as you would have to keep the class code around and execute it when objects are created.</p> <p>Yes, it is unexpected. But once the penny drops, it fits in perfectly with how Python works in general. In fact, it's a good teaching aid, and once you understand why this happens, you'll grok python much better.</p> <p>That said it should feature prominently in any good Python tutorial. Because as you mention, everyone runs into this problem sooner or later.</p>
53
2009-07-15T18:54:45Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,133,375
<p>This behavior is easy explained by:</p> <ol> <li>function (class etc.) declaration is executed only once, creating all default value objects</li> <li>everything is passed by reference</li> </ol> <p>So:</p> <pre><code>def x(a=0, b=[], c=[], d=0): a = a + 1 b = b + [1] c.append(1) print a, b, c </code></pre> <ol> <li>a doesn't change - every assignment call creates new int object - new object is printed</li> <li>b doesn't change - new array is build from default value and printed</li> <li>c changes - operation is performed on same object - and it is printed</li> </ol>
29
2009-07-15T19:15:25Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,133,737
<p>What you're asking is why this:</p> <pre><code>def func(a=[], b = 2): pass </code></pre> <p>isn't internally equivalent to this:</p> <pre><code>def func(a=None, b = None): a_default = lambda: [] b_default = lambda: 2 def actual_func(a=None, b=None): if a is None: a = a_default() if b is None: b = b_default() return actual_func func = func() </code></pre> <p>except for the case of explicitly calling func(None, None), which we'll ignore.</p> <p>In other words, instead of evaluating default parameters, why not store each of them, and evaluate them when the function is called?</p> <p>One answer is probably right there--it would effectively turn every function with default parameters into a closure. Even if it's all hidden away in the interpreter and not a full-blown closure, the data's got to be stored somewhere. It'd be slower and use more memory.</p>
21
2009-07-15T20:18:14Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,134,613
<p>It's a performance optimization. As a result of this functionality, which of these two function calls do you think is faster?</p> <pre><code>def print_tuple(some_tuple=(1,2,3)): print some_tuple print_tuple() #1 print_tuple((1,2,3)) #2 </code></pre> <p>I'll give you a hint. Here's the disassembly (see <a href="http://docs.python.org/library/dis.html">http://docs.python.org/library/dis.html</a>):</p> <h1><code>#</code>1</h1> <pre><code>0 LOAD_GLOBAL 0 (print_tuple) 3 CALL_FUNCTION 0 6 POP_TOP 7 LOAD_CONST 0 (None) 10 RETURN_VALUE </code></pre> <h1><code>#</code>2</h1> <pre><code> 0 LOAD_GLOBAL 0 (print_tuple) 3 LOAD_CONST 4 ((1, 2, 3)) 6 CALL_FUNCTION 1 9 POP_TOP 10 LOAD_CONST 0 (None) 13 RETURN_VALUE </code></pre> <blockquote> <p>I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs ?)</p> </blockquote> <p>As you can see, there <em>is</em> a performance benefit when using immutable default arguments. This can make a difference if it's a frequently called function or the default argument takes a long time to construct. Also, bear in mind that Python isn't C. In C you have constants that are pretty much free. In Python you don't have this benefit.</p>
19
2009-07-15T23:18:36Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,134,623
<p>I know nothing about the Python interpreter inner workings (and I'm not an expert in compilers and interpreters either) so don't blame me if I propose anything unsensible or impossible.</p> <p>Provided that python objects <strong>are mutable</strong> I think that this should be taken into account when designing the default arguments stuff. When you instantiate a list:</p> <pre><code>a = [] </code></pre> <p>you expect to get a <strong>new</strong> list referenced by <em>a</em>.</p> <p>Why should the a=[] in</p> <pre><code>def x(a=[]): </code></pre> <p>instantiate a new list on function definition and not on invocation? It's just like you're asking "if the user doesn't provide the argument then <em>instantiate</em> a new list and use it as if it was produced by the caller". I think this is ambiguous instead:</p> <pre><code>def x(a=datetime.datetime.now()): </code></pre> <p>user, do you want <em>a</em> to default to the datetime corresponding to when you're defining or executing <em>x</em>? In this case, as in the previous one, I'll keep the same behaviour as if the default argument "assignment" was the first instruction of the function (datetime.now() called on function invocation). On the other hand, if the user wanted the definition-time mapping he could write:</p> <pre><code>b = datetime.datetime.now() def x(a=b): </code></pre> <p>I know, I know: that's a closure. Alternatively Python might provide a keyword to force definition-time binding:</p> <pre><code>def x(static a=b): </code></pre>
68
2009-07-15T23:21:09Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,136,611
<p>I used to think that creating the objects at runtime would be the better approach. I'm less certain now, since you do lose some useful features, though it may be worth it regardless simply to prevent newbie confusion. The disadvantages of doing so are:</p> <p><strong>1. Performance</strong></p> <pre><code>def foo(arg=something_expensive_to_compute())): ... </code></pre> <p>If call-time evaluation is used, then the expensive function is called every time your function is used without an argument. You'd either pay an expensive price on each call, or need to manually cache the value externally, polluting your namespace and adding verbosity.</p> <p><strong>2. Forcing bound parameters</strong></p> <p>A useful trick is to bind parameters of a lambda to the <em>current</em> binding of a variable when the lambda is created. For example:</p> <pre><code>funcs = [ lambda i=i: i for i in range(10)] </code></pre> <p>This returns a list of functions that return 0,1,2,3... respectively. If the behaviour is changed, they will instead bind <code>i</code> to the <em>call-time</em> value of i, so you would get a list of functions that all returned <code>9</code>.</p> <p>The only way to implement this otherwise would be to create a further closure with the i bound, ie:</p> <pre><code>def make_func(i): return lambda: i funcs = [make_func(i) for i in range(10)] </code></pre> <p><strong>3. Introspection</strong></p> <p>Consider the code:</p> <pre><code>def foo(a='test', b=100, c=[]): print a,b,c </code></pre> <p>We can get information about the arguments and defaults using the <code>inspect</code> module, which </p> <pre><code>&gt;&gt;&gt; inspect.getargspec(foo) (['a', 'b', 'c'], None, None, ('test', 100, [])) </code></pre> <p>This information is very useful for things like document generation, metaprogramming, decorators etc.</p> <p>Now, suppose the behaviour of defaults could be changed so that this is the equivalent of:</p> <pre><code>_undefined = object() # sentinel value def foo(a=_undefined, b=_undefined, c=_undefined) if a is _undefined: a='test' if b is _undefined: b=100 if c is _undefined: c=[] </code></pre> <p>However, we've lost the ability to introspect, and see what the default arguments <em>are</em>. Because the objects haven't been constructed, we can't ever get hold of them without actually calling the function. The best we could do is to store off the source code and return that as a string.</p>
35
2009-07-16T10:05:09Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,137,164
<p>the shortest answer would probably be "definition is execution", therefore the whole argument makes no strict sense. as a more contrived example, you may cite this:</p> <pre><code>def a(): return [] def b(x=a()): print x </code></pre> <p>hopefully it's enough to show that not executing the default argument expressions at the execution time of the def statement isn't easy or doesn't make sense, or both.</p> <p>i agree it's a gotcha when you try to use default constructors, though.</p>
12
2009-07-16T12:19:23Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,139,730
<p>It may be true that:</p> <ol> <li>Someone is using every language/library feature, and</li> <li>Switching the behavior here would be ill-advised, but</li> </ol> <p>it is entirely consistent to hold to both of the features above and still make another point:</p> <ol> <li>It is a confusing feature and it is unfortunate in Python.</li> </ol> <p>The other answers, or at least some of them either make points 1 and 2 but not 3, or make point 3 and downplay points 1 and 2. <strong>But all three are true.</strong></p> <p>It may be true that switching horses in midstream here would be asking for significant breakage, and that there could be more problems created by changing Python to intuitively handle Stefano's opening snippet. And it may be true that someone who knew Python internals well could explain a minefield of consequences. <em>However,</em></p> <p>The existing behavior is not Pythonic, and Python is successful because very little about the language violates the principle of least astonishment anywhere <em>near</em> this badly. It is a real problem, whether or not it would be wise to uproot it. It is a design flaw. If you understand the language much better by trying to trace out the behavior, I can say that C++ does all of this and more; you learn a lot by navigating, for instance, subtle pointer errors. But this is not Pythonic: people who care about Python enough to persevere in the face of this behavior are people who are drawn to the language because Python has far fewer surprises than other language. Dabblers and the curious become Pythonistas when they are astonished at how little time it takes to get something working--not because of a design fl--I mean, hidden logic puzzle--that cuts against the intuitions of programmers who are drawn to Python because it <strong>Just Works</strong>.</p>
7
2009-07-16T19:17:59Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
1,145,781
<p>Actually, this is not a design flaw, and it is not because of internals, or performance.<br /> It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.</p> <p>As soon as you get to think into this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other object.</p> <p>In any case, Effbot has a very nice explanation of the reasons for this behavior in <a href="http://effbot.org/zone/default-values.htm">Default Parameter Values in Python</a>.<br /> I found it very clear, and I really suggest reading it for a better knowledge of how function objects work.</p>
1,037
2009-07-17T21:29:39Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
6,092,808
<p>This actually has nothing to do with default values, other than that it often comes up as an unexpected behaviour when you write functions with mutable default values.</p> <pre><code>&gt;&gt;&gt; def foo(a): a.append(5) print a &gt;&gt;&gt; a = [5] &gt;&gt;&gt; foo(a) [5, 5] &gt;&gt;&gt; foo(a) [5, 5, 5] &gt;&gt;&gt; foo(a) [5, 5, 5, 5] &gt;&gt;&gt; foo(a) [5, 5, 5, 5, 5] </code></pre> <p>No default values in sight in this code, but you get exactly the same problem.</p> <p>The problem is that <code>foo</code> is <em>modifying</em> a mutable variable passed in from the caller, when the caller doesn't expect this. Code like this would be fine if the function was called something like <code>append_5</code>; then the caller would be calling the function in order to modify the value they pass in, and the behaviour would be expected. But such a function would be very unlikely to take a default argument, and probably wouldn't return the list (since the caller already has a reference to that list; the one it just passed in).</p> <p>Your original <code>foo</code>, with a default argument, shouldn't be modifying <code>a</code> whether it was explicitly passed in or got the default value. Your code should leave mutable arguments alone unless it is clear from the context/name/documentation that the arguments are supposed to be modified. Using mutable values passed in as arguments as local temporaries is an extremely bad idea, whether we're in Python or not and whether there are default arguments involved or not.</p> <p>If you need to destructively manipulate a local temporary in the course of computing something, and you need to start your manipulation from an argument value, you need to make a copy.</p>
20
2011-05-23T04:24:30Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
9,791,799
<p>The solutions here are:</p> <ol> <li>Use <code>None</code> as your default value (or a nonce <code>object</code>), and switch on that to create your values at runtime; or</li> <li>Use a <code>lambda</code> as your default parameter, and call it within a try block to get the default value (this is the sort of thing that lambda abstraction is for).</li> </ol> <p>The second option is nice because users of the function can pass in a callable, which may be already existing (such as a <code>type</code>)</p>
12
2012-03-20T17:22:11Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
10,304,917
<p>This behavior is not surprising if you take the following into consideration:</p> <ol> <li>The behavior of read-only class attributes upon assignment attempts, and that</li> <li>Functions are objects (explained well in the accepted answer). </li> </ol> <p>The role of <strong>(2)</strong> has been covered extensively in this thread. <strong>(1)</strong> is likely the astonishment causing factor, as this behavior is not "intuitive" when coming from other languages.</p> <p><strong>(1)</strong> is described in the Python <a href="http://docs.python.org/tutorial/classes.html">tutorial on classes</a>. In an attempt to assign a value to a read-only class attribute:</p> <blockquote> <p>...all variables found outside of the innermost scope are read-only (<strong><em>an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged</em></strong>).</p> </blockquote> <p>Look back to the original example and consider the above points:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Here <code>foo</code> is an object and <code>a</code> is an attribute of <code>foo</code> (available at <code>foo.func_defs[0]</code>). Since <code>a</code> is a list, <code>a</code> is mutable and is thus a read-write attribute of <code>foo</code>. It is initialized to the empty list as specified by the signature when the function is instantiated, and is available for reading and writing as long as the function object exists. </p> <p>Calling <code>foo</code> without overriding a default uses that default's value from <code>foo.func_defs</code>. In this case, <code>foo.func_defs[0]</code> is used for <code>a</code> within function object's code scope. Changes to <code>a</code> change <code>foo.func_defs[0]</code>, which is part of the <code>foo</code> object and persists between execution of the code in <code>foo</code>.</p> <p>Now, compare this to the example from the documentation on <a href="http://docs.python.org/tutorial/controlflow.html#default-argument-values">emulating the default argument behavior of other languages</a>, such that the function signature defaults are used every time the function is executed:</p> <pre><code>def foo(a, L=None): if L is None: L = [] L.append(a) return L </code></pre> <p>Taking <strong>(1)</strong> and <strong>(2)</strong> into account, one can see why this accomplishes the the desired behavior: </p> <ul> <li>When the <code>foo</code> function object is instantiated, <code>foo.func_defs[0]</code> is set to <code>None</code>, an immutable object.</li> <li>When the function is executed with defaults (with no parameter specified for <code>L</code> in the function call), <code>foo.func_defs[0]</code> (<code>None</code>) is available in the local scope as <code>L</code>.</li> <li>Upon <code>L = []</code>, the assignment cannot succeed at <code>foo.func_defs[0]</code>, because that attribute is read-only. </li> <li>Per <strong>(1)</strong>, <strong><em>a new local variable also named <code>L</code> is created in the local scope</em></strong> and used for the remainder of the function call. <code>foo.func_defs[0]</code> thus remains unchanged for future invocations of <code>foo</code>.</li> </ul>
14
2012-04-24T19:43:13Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
11,334,749
<pre><code>&gt;&gt;&gt; def a(): &gt;&gt;&gt; print "a executed" &gt;&gt;&gt; return [] &gt;&gt;&gt; x =a() a executed &gt;&gt;&gt; def b(m=[]): &gt;&gt;&gt; m.append(5) &gt;&gt;&gt; print m &gt;&gt;&gt; b(x) [5] &gt;&gt;&gt; b(x) [5, 5] </code></pre>
3
2012-07-04T19:51:30Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
11,416,002
<p>AFAICS no one has yet posted the relevant part of the <a href="http://docs.python.org/reference/compound_stmts.html#function-definitions">documentation</a>:</p> <blockquote> <p><strong>Default parameter values are evaluated when the function definition is executed.</strong> This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function [...]</p> </blockquote>
130
2012-07-10T14:50:42Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
13,518,071
<p>1) The so-called problem of "Mutable Default Argument" is in general a special example demonstrating that:<br> "All functions with this problem <strong>suffer also from similar side effect problem on the actual parameter</strong>,"<br> That is against the rules of functional programming, usually undesiderable and should be fixed both together.</p> <p>Example:</p> <pre><code>def foo(a=[]): # the same problematic function a.append(5) return a &gt;&gt;&gt; somevar = [1, 2] # an example without a default parameter &gt;&gt;&gt; foo(somevar) [1, 2, 5] &gt;&gt;&gt; somevar [1, 2, 5] # usually expected [1, 2] </code></pre> <p><strong>Solution</strong>: a <strong>copy</strong><br> An absolutely safe solution is to <strong><code>copy</code></strong> or <strong><code>deepcopy</code></strong> the input object first and then to do whatever with the copy.</p> <pre><code>def foo(a=[]): a = a[:] # a copy a.append(5) return a # or everything safe by one line: "return a + [5]" </code></pre> <p>Many builtin mutable types have a copy method like <code>some_dict.copy()</code> or <code>some_set.copy()</code> or can be copied easy like <code>somelist[:]</code> or <code>list(some_list)</code>. Every object can be also copied by <code>copy.copy(any_object)</code> or more thorough by <code>copy.deepcopy()</code> (the latter useful if the mutable object is composed from mutable objects). Some objects are fundamentally based on side effects like "file" object and can not be meaningfully reproduced by copy. <a href="http://effbot.org/pyfaq/how-do-i-copy-an-object-in-python.htm">copying</a></p> <p>Example problem for <a href="http://stackoverflow.com/q/13484107/448474">a similar SO question</a></p> <pre><code>class Test(object): # the original problematic class def __init__(self, var1=[]): self._var1 = var1 somevar = [1, 2] # an example without a default parameter t1 = Test(somevar) t2 = Test(somevar) t1._var1.append([1]) print somevar # [1, 2, [1]] but usually expected [1, 2] print t2._var1 # [1, 2, [1]] but usually expected [1, 2] </code></pre> <p>It shouldn't be neither saved in any <em>public</em> attribute of an instance returned by this function. (Assuming that <em>private</em> attributes of instance should not be modified from outside of this class or subclasses by convention. i.e. <code>_var1</code> is a private attribute )</p> <p>Conclusion:<br> Input parameters objects shouldn't be modified in place (mutated) nor they should not be binded into an object returned by the function. (If we prefere programming without side effects which is strongly recommended. see <a href="http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29">Wiki about "side effect"</a> (The first two paragraphs are relevent in this context.) .)</p> <p>2)<br> Only if the side effect on the actual parameter is required but unwanted on the default parameter then the useful solution is <code>def ...(var1=None):</code> <code>if var1 is None:</code> <code>var1 = []</code> <a href="http://effbot.org/zone/default-values.htm#what-to-do-instead">More..</a></p> <p>3) In some cases is <a href="http://effbot.org/zone/default-values.htm#valid-uses-for-mutable-defaults">the mutable behavior of default parameters useful</a>.</p>
20
2012-11-22T18:09:04Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
14,336,301
<p>You can get round this by replacing the object (and therefore the tie with the scope):</p> <pre><code>def foo(a=[]): a = list(a) a.append(5) return a </code></pre> <p>Ugly, but it works.</p>
10
2013-01-15T11:02:03Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
15,133,978
<p>A simple workaround using None</p> <pre><code>&gt;&gt;&gt; def bar(b, data=None): ... data = data or [] ... data.append(b) ... return data ... &gt;&gt;&gt; bar(3) [3] &gt;&gt;&gt; bar(3) [3] &gt;&gt;&gt; bar(3) [3] &gt;&gt;&gt; bar(3, [34]) [34, 3] &gt;&gt;&gt; bar(3, [34]) [34, 3] </code></pre>
11
2013-02-28T11:10:16Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
17,782,210
<p>This "bug" gave me a lot of overtime work hours! But I'm beginning to see a potential use of it (but I would have liked it to be at the execution time, still)</p> <p>I'm gonna give you what I see as a useful example.</p> <pre><code>def example(errors=[]): # statements # Something went wrong mistake = True if mistake: tryToFixIt(errors) # Didn't work.. let's try again tryToFixItAnotherway(errors) # This time it worked return errors def tryToFixIt(err): err.append('Attempt to fix it') def tryToFixItAnotherway(err): err.append('Attempt to fix it by another way') def main(): for item in range(2): errors = example() print '\n'.join(errors) main() </code></pre> <p>prints the following</p> <pre><code>Attempt to fix it Attempt to fix it by another way Attempt to fix it Attempt to fix it by another way </code></pre>
6
2013-07-22T07:35:28Z
[ "python", "language-design", "least-astonishment" ]
"Least Astonishment" and the Mutable Default Argument
1,132,941
<p>Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:</p> <pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices would expect this function to always return a list with only one element: <code>[5]</code>. The result is instead very different, and very astonishing (for a novice):</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo() [5, 5, 5] &gt;&gt;&gt; foo() [5, 5, 5, 5] &gt;&gt;&gt; foo() </code></pre> <p>A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)</p> <p><strong>Edit</strong>: </p> <p>Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:</p> <pre><code>&gt;&gt;&gt; def a(): ... print "a executed" ... return [] ... &gt;&gt;&gt; &gt;&gt;&gt; def b(x=a()): ... x.append(5) ... print x ... a executed &gt;&gt;&gt; b() [5] &gt;&gt;&gt; b() [5, 5] </code></pre> <p>To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?</p> <p>Doing the binding inside the function would mean that <code>x</code> is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the <code>def</code> line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.</p> <p>The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.</p>
1,504
2009-07-15T18:00:37Z
18,372,696
<p>I think the answer to this question lies in how python pass data to parameter (pass by value or by reference), not mutability or how python handle the "def" statement.</p> <p>A brief introduction. First, there are two type of data types in python, one is simple elementary data type, like numbers, and another data type is objects. Second, when passing data to parameters, python pass elementary data type by value, i.e., make a local copy of the value to a local variable, but pass object by reference, i.e., pointers to the object.</p> <p>Admitting the above two points, let's explain what happened to the python code. It's only because of passing by reference for objects, but has nothing to do with mutable/immutable, or arguably the fact that "def" statement is executed only once when it is defined.</p> <p>[] is an object, so python pass the reference of [] to <code>a</code>, i.e., <code>a</code> is only a pointer to [] which lies in memory as an object. There is only one copy of [] with, however, many references to it. For the first foo(), the list [] is changed to <a href="http://effbot.org/zone/default-values.htm">1</a> by append method. But Note that there is only one copy of the list object and this object now becomes <a href="http://effbot.org/zone/default-values.htm">1</a>. When running the second foo(), what effbot webpage says (items is not evaluated any more) is wrong. <code>a</code> is evaluated to be the list object, although now the content of the object is <a href="http://effbot.org/zone/default-values.htm">1</a>. This is the effect of passing by reference! The result of foo(3) can be easily derived in the same way.</p> <p>To further validate my answer, let's take a look at two additional codes.</p> <p>====== No. 2 ========</p> <pre><code>def foo(x, items=None): if items is None: items = [] items.append(x) return items foo(1) #return [1] foo(2) #return [2] foo(3) #return [3] </code></pre> <p><code>[]</code> is an object, so is <code>None</code> (the former is mutable while the latter is immutable. But the mutability has nothing to do with the question). None is somewhere in the space but we know it's there and there is only one copy of None there. So every time foo is invoked, items is evaluated (as opposed to some answer that it is only evaluated once) to be None, to be clear, the reference (or the address) of None. Then in the foo, item is changed to [], i.e., points to another object which has a different address. </p> <p>====== No. 3 =======</p> <pre><code>def foo(x, items=[]): items.append(x) return items foo(1) # returns [1] foo(2,[]) # returns [2] foo(3) # returns [1,3] </code></pre> <p>The invocation of foo(1) make items point to a list object [] with an address, say, 11111111. the content of the list is changed to <a href="http://effbot.org/zone/default-values.htm">1</a> in the foo function in the sequel, but the address is not changed, still 11111111. Then foo(2,[]) is coming. Although the [] in foo(2,[]) has the same content as the default parameter [] when calling foo(1), their address are different! Since we provide the parameter explicitly, <code>items</code> has to take the address of this new <code>[]</code>, say 2222222, and return it after making some change. Now foo(3) is executed. since only <code>x</code> is provided, items has to take its default value again. What's the default value? It is set when defining the foo function: the list object located in 11111111. So the items is evaluated to be the address 11111111 having an element 1. The list located at 2222222 also contains one element 2, but it is not pointed by items any more. Consequently, An append of 3 will make <code>items</code> [1,3]. </p> <p>From the above explanations, we can see that the <a href="http://effbot.org/zone/default-values.htm">effbot</a> webpage recommended in the accepted answer failed to give a relevant answer to this question. What is more, I think a point in the effbot webpage is wrong. I think the code regarding the UI.Button is correct:</p> <pre><code>for i in range(10): def callback(): print "clicked button", i UI.Button("button %s" % i, callback) </code></pre> <p>Each button can hold a distinct callback function which will display different value of <code>i</code>. I can provide an example to show this:</p> <pre><code>x=[] for i in range(10): def callback(): print(i) x.append(callback) </code></pre> <p>If we execute <code>x[7]()</code> we'll get 7 as expected, and <code>x[9]()</code> will gives 9, another value of <code>i</code>.</p>
5
2013-08-22T05:58:41Z
[ "python", "language-design", "least-astonishment" ]