I spent ages experimenting and I have a theory about why you're getting this error. I'm not certain but this does explain why it works for c
and not for d
. I hope this helps you, comment if you disagree :)
def Tuple(this):
print(a) # this always works
try:
print(b) # this always gives an error
except NameError:
print("...b is not defined")
try:
return tuple(this) # this only gives an error for d and e
except NameError:
print("...couldn't make it a tuple")
a = (1,2)
class Foo(object):
b = (3,4)
c = Tuple((i,j) for j in b for i in a)
d = Tuple((i,j) for i in a for j in b)
e = Tuple((i,j,k) for i in a for j in b for k in (5, 6))
f = Tuple((i,j,k) for j in b for i in (5, 6) for k in a)
print("\nc:", c,"\nd:", d,"\ne:", e,"\nf:", f)
What happened: every time I called the Tuple()
function, b
was not defined, but a
was always defined. This explains why you get an error for d
and e
but it doesn't explain why c
and f
work even though b
is 'not defined'
My theory: The first for
loop is calculated before the whole thing is converted into a tuple. For example, if you tried to do this: Tuple((a, b, c) for a in loop1, for b in loop2 for c in loop3)
, in the Foo class it would calculate for a in loop1
first, then it would move to the foo and calculate the loops 2 and 3.
In summary:
- does first for loop
- moves to tuple function
- does the remaining loops
- the error occurs if a variable in the 2nd or 3rd loop is in class Foo