I'm writing a simple class in Python 2.7.13 and I ran into a surprising error:
class X(object):
T = 'test {}'
A1 = [x for x in T] # ok
A2 = tuple([x for x in T]) # ok
A3 = tuple(x for x in T) # ok
B1 = [T.format(x) for x in (1,2)] # ok
B2 = tuple([T.format(x) for x in (1,2)]) # ok
B3 = tuple(T.format(x) for x in (1,2)) # NameError
All of the above work except the line defining B3 which gives NameError: global name 'T' is not defined
.
I'm curious exactly why that line is the only one giving an error. I had been writing tuple(...)
as if it were equivalent to tuple([...])
but it seems that they are not the same after all.
I also checked and Python 3.4.3 gives an error on the lines defining B1
, B2
and B3
which at least seems more consistent.