1

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.

nonagon
  • 3,271
  • 1
  • 29
  • 42
  • Just don't use comprehensions and genexps inside a class definition. It doesn't work. There's a good dupe around here somewhere. – user2357112 Feb 26 '18 at 18:34
  • The issue is not the tuple call, but what's inside it. `[T.format(x)...]` is a list comprehension, whereas `(T.format(x)...)` is a generator expression. Python lets you omit the surrounding parentheses if a generator expression is the only parameter to a callable. – Daniel Roseman Feb 26 '18 at 18:34
  • 2
    In Python 3, you'd get the same error for all three `B*` definitions. – Martijn Pieters Feb 26 '18 at 18:35
  • And @user2357112: was faster in locating my own answer than I was. :-) – Martijn Pieters Feb 26 '18 at 18:35
  • What about the `A*` definitions? It's interesting that they work in all pythons. @MartijnPieters your other answer is remarkably complete! So I'm not arguing this is a duplicate, I just thought a brief answer to why the `A*` definitions are okay might be helpful for others. – nonagon Feb 26 '18 at 18:51
  • @nonagon: there `T` is the iterable for the top-level `for` loop, which is passed into the function that is generated to handle the generator expression. – Martijn Pieters Feb 26 '18 at 18:55
  • @MartijnPieters gotcha - makes sense. Thank you!! – nonagon Feb 26 '18 at 19:48

0 Answers0