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 Mi... | 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 th... | 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 >= max:
last_max = max
max = n * (max + 1)
digits += 1
result = ''
i -= last_max
while digits:
digits -= 1
re... | 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 th... | 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 ... | 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 th... | 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 > n:
return chars, n
chars += 1
n -= cnt
def conv_base(chars, n, values):
ret = []
for i in ra... | 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 th... | 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 th... | 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 < group_size:
break
x -= group_size
group_size *= len(alphabet)
letters = []
for i in range(num_letters):
x, m = divmod(x... | 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 th... | 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 combi... | 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 th... | 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 => A, or 1 in base [0ABCDEF]
7 => AA, or 8 in base [0ABCD... | 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 th... | 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>=0:
result += alph[x%ct]
... | 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>() a... | 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.dja... | 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
de... | 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 = {... | 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
de... | 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 Sp... | 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
de... | 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
@classmeth... | 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-package... | 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... | 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-package... | 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... | 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-package... | 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 sam... | 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>
... | 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>
... | 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(...... | 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... | 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... | 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 Cry... | 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... | 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 condit... | 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 ... | 4 | 2009-07-15T10:50:04Z | 1,130,722 | <p>In both cases, most of the code should Just Work™. 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 thing... | 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 ... | 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 ... | 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.... | 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 ... | 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 ... | 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 ... | 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
ra... | 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
ra... | 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!
... | 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
ra... | 5 | 2009-07-15T11:04:53Z | 1,130,795 | <p>First one is also obvious, as second one e.g.</p>
<pre><code>>>> try:
... socket.socket().connect(("0.0.0.0", 0))
... except socket.error:
... print "socket error!!!"
...
socket error!!!
>>>
</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... | 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... | 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... | 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 c... | 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... | 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 = ""
_h... | 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... | 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 ... | 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", "stupi... | 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 Bo... | 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", "stupi... | 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", "stupi... | 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 alg... | -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", "stupi... | 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="n... | 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 g... | 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 g... | 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... | 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 g... | 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 you... | 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 g... | 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... | 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 g... | 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 g... | 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)
... | 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 g... | 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 ... | -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 g... | 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 filesyst... | 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 g... | 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 g... | 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=81... | 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 eac... | 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 w... | 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://... | 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... | 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>del... | 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... | 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... | 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... | 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... | 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_Inte... | -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... | 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):
... | 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... | 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... | 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 a... | 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... | 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 stude... | 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... | 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.wiki... | 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... | 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... | 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 depen... | 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... | 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. Yo... | 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... | 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(studen... | 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 formenco... | 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
... | 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 l... | 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&sort=-stars&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine... | 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">ht... | 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&sort=-stars&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine... | 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&sort=-stars&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine... | 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&sort=-stars&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 im... | 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&sort=-stars&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary">anytime soon</a>. There is an <a href="http://code.google.com/appengine... | 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 ... | 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... | 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-pygtkgenericcel... | 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 fo... | 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... | 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 fo... | 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 fo... | 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,... | 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 & 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 & B trade the digital signatures they have, and check it ... | 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 ... | 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 & 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 & B trade the digital signatures they have, and check it ... | 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 digi... | 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 diff... | 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", ... | 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 diff... | 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>
... | 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 diff... | 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
</co... | 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 diff... | 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... | 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 diff... | 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 (se... | 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 diff... | 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... | 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 diff... | 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 fo... | 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 diff... | 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 ex... | 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 diff... | 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 unfortu... | 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 diff... | 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... | 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 diff... | 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>>>> def foo(a):
a.append(5)
print a
>>> a = [5]
>>> foo(a)
[5, 5]
>>> foo(a)
[5, 5, 5]
... | 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 diff... | 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 ... | 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 diff... | 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 extensive... | 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 diff... | 1,504 | 2009-07-15T18:00:37Z | 11,334,749 | <pre><code>>>> def a():
>>> print "a executed"
>>> return []
>>> x =a()
a executed
>>> def b(m=[]):
>>> m.append(5)
>>> print m
>>> b(x)
[5]
>>> 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 diff... | 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 evalu... | 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 diff... | 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 s... | 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 diff... | 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 diff... | 1,504 | 2009-07-15T18:00:37Z | 15,133,978 | <p>A simple workaround using None</p>
<pre><code>>>> def bar(b, data=None):
... data = data or []
... data.append(b)
... return data
...
>>> bar(3)
[3]
>>> bar(3)
[3]
>>> bar(3)
[3]
>>> bar(3, [34])
[34, 3]
>>> 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 diff... | 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 = T... | 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 diff... | 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 t... | 5 | 2013-08-22T05:58:41Z | [
"python",
"language-design",
"least-astonishment"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.