Fun with python

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 = ([],[])

# Modifying a tuple ?
a[0] += [1]

print a

Weird list references:

a = [[None]*4]*3
a[0][0] = 1

print a

Import madness:

* in

* in
import mod1
def set_foo(i):
mod1.FOO = i

* in
from mod1 import *
import mod2
print FOO

Run "python"

Weird variable scoping:

* in
a = 3
def foo():
return a

if __name__ == "__main__":
for a in range(3):
print foo()

* in
from mod1 import *
a = 6
print foo()

Compare "python" and "python"

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?

Tags: ,

One Response to “Fun with python”

  1. Thx1138 says:

    In the first example, you don’t modify the tuple, really.
    Instead you modify the list which is referenced by the tuple.
    That’s all.