Fun python snippets
Here is a short list of python WTF’s i often come across in my own code, debugging
those is quite hard..
Tuples are immutable ?
a = ([],[]) try: # Modifying a tuple ? a[0] += [1] except: pass print a
Weird list references:
a = [[None]*4]*3 a[0][0] = 1 print a
Import madness:
* in mod1.py: FOO=1 * in mod2.py: import mod1 def set_foo(i): mod1.FOO = i * in mod3.py: from mod1 import * import mod2 mod2.set_foo(2) print FOO Run "python mod3.py"
Weird variable scoping:
* in mod1.py: a = 3 def foo(): return a if __name__ == "__main__": for a in range(3): print foo() * in mod2.py from mod1 import * a = 6 print foo() Compare "python mod1.py" and "python mod2.py"
Of course these snippets are a bit convoluted, but I often find these patterns appearing randomly..
How much of them have you got right without looking at the answer before?