Python Gotchas!
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]:
In [2]:
x = 257
y = 257
# x is y?
In [3]:
x is y
Out[3]:
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)
In [9]:
# Why?
board[0] is board[1] is board [2]
Out[9]:
Mutable Default Arguments¶
In [10]:
def append_derp(l=[]):
l.append('derp')
return l
In [11]:
append_derp()
# append_derp() ?
Out[11]:
In [12]:
append_derp()
Out[12]:
In [13]:
append_derp.__defaults__
Out[13]:
In [14]:
_[0].append('robot')
append_derp()
Out[14]:
Scope¶
In [15]:
v = 1
def return_v():
return v
return_v()
Out[15]:
In [16]:
v = 1
def return_v():
v += 1
return v
return_v()
In [1]:
v = 1
def return_v():
global v
v += 1
return v
return_v()
Out[1]:
In [2]:
v = 1
def return_v():
v = 5
return v
return_v()
Out[2]: