Thursday, September 26, 2013

variable dis-assignment

>>> def foo():
...    a = 1
...    del a
...    return a
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in foo
UnboundLocalError: local variable 'a' referenced before assignment


Friday, September 6, 2013

unicodebreakers

Just when you thought it was safe to unicode....
>>> unicode(3)
u'3'
>>> unicode(3, errors='replace')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, int found

If you prefer Python3:
>>> str(3)
'3'
>>> str(3, errors='replace')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to str: need bytes, bytearray or buffer-like object, int found

Thursday, September 5, 2013

random failure

>>> random.choice({0:1, 2:3})
1
>>> random.choice({0:1, 2:3})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\random.py", line 274, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty 
KeyError: 1

Alright pythonauts, why does this fail sometimes and succeed others? :-)