Skip to content

Instantly share code, notes, and snippets.

@pfctdayelise
Created February 19, 2014 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfctdayelise/9085928 to your computer and use it in GitHub Desktop.
Save pfctdayelise/9085928 to your computer and use it in GitHub Desktop.
Demonstration and workaround of Python bug 4806
# written in python2.7
def bad(n):
if n == 1:
raise ValueError('n is 1!')
if n == 2:
raise TypeError('n is 2!')
return n, 2*n
def bads(vs):
for v in vs:
yield bad(v)
print "using zip(*gen)"
a, b = zip(*bads([3]))
assert a == (3,)
assert b == (6,)
print "a and b as expected"
try:
a, b = zip(*bads([1]))
except Exception as e:
print repr(e)
try:
a, b = zip(*bads([2]))
except Exception as e:
print repr(e)
print "\nusing zip(*list(gen))"
a, b = zip(*list(bads([3])))
assert a == (3,)
assert b == (6,)
print "a and b as expected"
try:
a, b = zip(*list(bads([1])))
except Exception as e:
print repr(e)
try:
a, b = zip(*list(bads([2])))
except Exception as e:
print repr(e)
using zip(*gen)
a and b as expected
ValueError('n is 1!',)
TypeError('zip() argument after * must be a sequence, not generator',)
using zip(*list(gen))
a and b as expected
ValueError('n is 1!',)
TypeError('n is 2!',)
===========
The moral is: convert calls from zip(*gen) to zip(*list(gen)) to get the correct errors
propagating up. It's a shame it has to be done but until http://bugs.python.org/issue4806
is fixed there is no alternative!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment