Re: bug or feature?



beza1e1:

Coming back from a bug hunt, i am not sure what to think of this python
behaviour. Here is a demo program:

class A:
   def __init__(self, lst=[]):
      self.lst = lst

a = A()
b = A()
b.lst.append("hallo")
print a.lst # output: ["hallo"]

The point seems to be, that lst=[] creates a class attribute (correct
name?), which is shared by all instances of A. So a.lst ist the same
object as b.lst, despite the fact, that object a is different to object
b.

Fredrik Lundh wrote:
Steve Holden wrote:


Interestingly I couldn't find this in the FAQ, though it *is* a
frequently-asked question [note: my not finding it doesn't guarantee
it's not there].


it's there:

    http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects

(maybe "default values" should be changed to "default argument values")

I couldn't believe it wasn't, but you're right: it should be easier to find, and a change of wording may do that.

regards
 Steve
--
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/

.



Relevant Pages

  • Re: [Full-Disclosure] viruses being sent to this list
    ... The fact that Len et al. care a LOT about keeping the channel ... lists. ... They can't guarantee the quality of the posts. ... Regards, ...
    (Full-Disclosure)
  • Re: Behringer Amps
    ... it as meaning that he regards an earth leak as sufficient ... grounds (ahem) to have it repaired. ... The wording isn't ...
    (alt.guitar.bass)
  • Re: View on opening file
    ... at least not without some code and then you have no guarantee that your users will have code enabled. ... Best regards ... John Goldsmith (Visio MVP) ...
    (microsoft.public.visio.general)
  • Re: More Nvidia issues on 9.1
    ... me it is explained may not be the right wording. ... The kernel will be build ...
    (alt.os.linux.suse)
  • Re: replace newlines by <BR>
    ... but no guarantee as I did not test it. ... Best Regards, ... Lucas ...
    (alt.php)