Erich Schubert: Python pitfall of the day: <tt>def function(var= )</tt>
I was hunting an odd bug in a python program of mine.
Here's a condensed code snippet for explanation:
class odd:
def __init__(self, a, b= ):
self.b = b
self.b["a"]=a
one = odd(1)
two = odd(2)
print one.b["a"]
That code looks reasonable, doesn't it? The parameter "a" is required, but
other parameters can be given in a hash. So what output would you expect?
The output is 2. The reason is as follows:
Python creates an empty hash, and b is a reference to this hash per
default. To the same hash each time. So the code is basically equivalent to
class odd2:
default_for_b_in_init =
def __init__(self, a, b=default_for_b_in_init):
self.b = b
self.b["a"]=a
and not (as I had expected):
class odd3:
def __init__(self, a, b=None):
if not b: b =
self.b = b
self.b["a"]=a
Obviously, both behaviours make sense, and the python way is somewhat
consequenter.
So be careful when using default values in functions!
Non-reference types such as integers are fine, so is None, and of course
any outside objects you want to be the same for each call. Don't assume
the def statement will create any new object.
Even shorter example:
def test(a, b= ):
print b
b["a"]=a
test(1)
test(2)
will result in the output
'a': 1again there is only a single hash b.
with a small problem at the top edge of screen due to lack of space there.
Update: Level 15 in 14:01 Minutes. The schema works perfectly, you have to
touch each node at most twice (once when discovering, and maybe switch place
with a sibling when discovering the new neighbours). All changes are local,
and you don't actually look at the lines, just at the colored nodes.
Unless of course you run out of space and have to rearrange.