1

Example first:

class Asdf(object):
    def __enter__(self):
        print("Enter")
        return self

    def __exit__(self, *args):
        print("Exit")

    def get_stuff(self):
        return range(10)


class Moo(object):
    with Asdf() as x:

        a = x.get_stuff()  # Works

        b = ['asdf' for _ in range(3)]  # Works

        c = []
        for _ in range(3):
            c.append(x.get_stuff())  # Works

        d = [x.get_stuff() for _ in range(3)]  # NameError: name 'x' is not defined


m = Moo()
print(m.a)
print(m.b)
print(m.c)
print(m.d)

When I run this in Python 2.7.14, I get the expected result:

Enter
Exit
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
['asdf', 'asdf', 'asdf']
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

However, when I run it using Python 3.6.3, the list comprehension fails:

Enter
Exit
Traceback (most recent call last):
  File "tmp.py", line 14, in <module>
    class Moo(object):
  File "tmp.py", line 25, in Moo
    d = [x.get_stuff() for _ in range(3)]  # NameError: name 'x' is not defined
  File "tmp.py", line 25, in <listcomp>
    d = [x.get_stuff() for _ in range(3)]  # NameError: name 'x' is not defined
NameError: name 'x' is not defined

Have the rules for list comprehensions changed in Python 3? Why can't I use x inside the list comprehension in Python 3?

rudolfbyker
  • 2,034
  • 1
  • 20
  • 25
  • It works fine in Python-3.7. Are you sure the list comprehension is running inside the context-manager? – Mazdak Mar 11 '18 at 20:41
  • Wow OK, I agree that my question is a duplicate. The answers there are satisfactory. It just kind of sucks, since I searched and did not find the other question. – rudolfbyker Mar 11 '18 at 20:57
  • @Kasramvd I don't see anything in the Python 3.7 changelog that would indicate why it works in 3.7 and not in 3.6: https://docs.python.org/dev/whatsnew/3.7.html – rudolfbyker Mar 11 '18 at 21:12

0 Answers0