3 ms·
``print a``? The inner `a` is the same reference as the outer `a`. a = 1; def foo(): b = a; return b foo() is a >> True This gets hairy when referr
by mattdeboard 13y ago
``print a``? The inner `a` is the same reference as the outer `a`.
a = 1;
def foo(): b = a; return b
foo() is a
>> True
This gets hairy when referring to mutable types:
a = []
def foo(): b = a; return b
foo().append(1)
a
>> [3]
Compare to immutable types:
c = ()
def bar(): d = c; return d
bar() + (1,)
c
>> ()
- agumonkey 13y agoI understand the context, but isn't it unfair to compare `append` and `+` ? Python is not clojure or sml, I think people assume mutability, and using foo() + [1] will consistently build fresh objects in both cases.
- mattdeboard 13y agoNo, I don't think it's unfair because "fairness" has nothing to do with anything. I was simply illustrating how using a mutable data structure defined in an outer scope can bite you.
- agumonkey 13y agoFair enough. May I mention the default parameter bite too. It's hard to notice at first.