Python Gotchas!

  |   Source

Python behaving in ways you might not expect

All credit goes to Amy Hanlon for original talk given at PyCon 2015

Identity

In [1]:
a = 256
b = 256
a is b
Out[1]:
True
In [2]:
x = 257
y = 257
# x is y?
In [3]:
x is y
Out[3]:
False

Mutability

In [4]:
row = [""] * 3
row
Out[4]:
['', '', '']
In [5]:
board = [row] * 3
for i in board: print(i)
['', '', '']
['', '', '']
['', '', '']
In [6]:
print(board[0])
print(board[0][0])
['', '', '']

In [7]:
board[0][0] = 'X'
# board?
In [8]:
for i in board: print(i)
['X', '', '']
['X', '', '']
['X', '', '']
In [9]:
# Why?
board[0] is board[1] is board [2]
Out[9]:
True

Mutable Default Arguments

In [10]:
def append_derp(l=[]):
    l.append('derp')
    return l
In [11]:
append_derp()
# append_derp() ?
Out[11]:
['derp']
In [12]:
append_derp()
Out[12]:
['derp', 'derp']
In [13]:
append_derp.__defaults__
Out[13]:
(['derp', 'derp'],)
In [14]:
_[0].append('robot')

append_derp()
Out[14]:
['derp', 'derp', 'robot', 'derp']

Scope

In [15]:
v = 1
def return_v():
    return v

return_v()
Out[15]:
1
In [16]:
v = 1
def return_v():
    v += 1
    return v

return_v()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-16-9893d23ceb29> in <module>()
      4     return v
      5 
----> 6 return_v()

<ipython-input-16-9893d23ceb29> in return_v()
      1 v = 1
      2 def return_v():
----> 3     v += 1
      4     return v
      5 

UnboundLocalError: local variable 'v' referenced before assignment
In [1]:
v = 1
def return_v():
    global v
    v += 1
    return v

return_v()
Out[1]:
2
In [2]:
v = 1
def return_v():
    v = 5
    return v

return_v()
Out[2]:
5
Comments powered by Disqus