arguments - Why does initializing a variable via a python default variable keep state across object instantiation? -
i hit interesting python bug today in instantiating class repeatedly appears holding state. in later instantiation calls variable defined.
i boiled down issue following class/shell interaction. realize not best way initialize class variable, sure should not behaving this. true bug or "feature"? :d
tester.py:
class tester(): def __init__(self): self.mydict = self.test() def test(self,out={}): key = "key" in ['a','b','c','d']: if key in out: out[key] += ','+i else: out[key] = return out
python prompt:
python 2.6.6 (r266:84292, oct 6 2010, 00:44:09) [gcc 4.2.1 (apple inc. build 5664)] on darwin >>> import tester >>> t = tester.tester() >>> print t.mydict {'key': 'a,b,c,d'} >>> t2 = tester.tester() >>> print t2.mydict {'key': 'a,b,c,d,a,b,c,d'}
it feature pretty python users run once or twice. main usage caches , avoid repetitive lengthy calculations (simple memoizing, really), although sure people have found other uses it.
the reason def
statement gets executed once, when function defined. initializer value gets created once. reference type (as opposed immutable type cannot change) list or dictionary, ends visible , surprising pitfall, whereas value types, goes unnoticed.
usually, people work around this:
def test(a=none): if none: = {} # ... etc.
Comments
Post a Comment