--=-uNM1Q6eCX9JH/wGWUYU9 Content-Type: text/plain Hello. I have found a rather annoying bug in Python, present in both Python 1.5 and Python 2.0. If a class has an argument with a default of an empty dictionary, then all instances of the same class will point to the same dictionary, unless the dictionary is explictly defined by the constructor. I attach a piece of code that demostrates the problem --=-uNM1Q6eCX9JH/wGWUYU9 Content-Type: text/x-python Content-Disposition: attachment; filename=test.py Content-Transfer-Encoding: 7bit """ Bug description: A class is defined. in the __init__ method, we define an options "attribs" argument, which defaults to {}. We create two instances of class foo, each of them without argument. we then modify the attribs attribute in one of them. in a suprising manner, the change if reflected in BOTH instances, where it should only appear in the first one. Workaround: explictly define an empty dictionary as the argument, or define the empty dictionary inside the method body. """ class foo: def __init__(self,attribs={}): self.attribs=attribs; return None; print ""; print "Defining Two instances of class foo:"; print "a=foo()" print "b=foo()" a=foo(); b=foo(); print ""; print "The 'attribs' attribute of both looks like this:"; print "a.attribs = %s" % a.attribs print "b.attribs = %s" % b.attribs print "" print "Now we modify 'attribs' in a:" print 'a.attribs["bug"]= "exists"'; a.attribs["bug"]= "exists"; print "" print "Now, things should now look like this:" print "a.attribs = %s" % a.attribs print "b.attribs = %s" % "{}"; print "" print "However, things look like this:" print "a.attribs = %s" % a.attribs print "b.attribs = %s" % b.attribs --=-uNM1Q6eCX9JH/wGWUYU9--
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4