Python Surprises

Python is a very intuitive language to code in, however there are some surprises that might catch you off guard. This article lists a few of the ones I find interesting. Many such articles have been published and there are links to some of them at the bottom of this page.

 

In Python for and while loops are not blocks. This means that variables defined within a loop still exist after that loop ends.

for i in range(3):
  pass
i
#===> 2

while True:
  a = 42
  break
a
#===> 42

 

Python’s for loop also accepts an else statement that only executes if the loop runs to completion.

for i in range(3):
  if i == 1:
    break
else:
  print "Else not executed here because the for loop ended with a break."

for i in range(3):
  pass
else:
  print "This will print because the loop completed successfully."

 

Booleans can act like integers, but only sometimes.

isinstance(False, bool)
#===> True
isinstance(False, int)
#===> True

a = True
b = True
a + b
#===> 2
a == 1
#===> True
a is 1
#===> False

 

Tuples always need commas.

a = (1)
type(a)
#===> integer

b = (1,)
type(b)
#===> tuple

 

+= vs + with mutable objects

a = [1, 2, 3]
id(a)
#===> 140415741190800
a += [4]
id(a)
#===> 140415741190800
a = a + [5]
id(a)
#===> 140415741191304

 

Default arguments are assigned when a function is defined, not when it is evaluated.

from time import time, sleep

def test(a=time()):
  print a

test()
#===> 1299590594.48
sleep(3)
test()
#===> 1299590594.48
# a is bound to time() at def, so will always return the same value

 

Tuple object does not support item assignment… or does it?

a = ([42],)
a[0] += [43, 44]
#===> TypeError: 'tuple' object does not support item assignment
a
#===> ([42, 43, 44],)

 

Links

Here are links to similar articles, in no particular order.

Python Pitfalls
Stack Overflow – Python Gotchas and Landmines
Python Warts
Charming Python: Python Elegance and Warts Part 1 and Part 2
Stack Overflow – Hidden Features of Python
When Pythons Attack
Python Gotchas
10 Python Quirks
Python Idioms and Efficiency
bool is int

* Most of these will only be “surprises” to newer Python programmers.
** These are not necessarily problems/warts/bugs in Python.

Advertisements