Skip to content

Instantly share code, notes, and snippets.

@eiiches
Created August 8, 2011 16:39
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 eiiches/1132136 to your computer and use it in GitHub Desktop.
Save eiiches/1132136 to your computer and use it in GitHub Desktop.
List Comprehension / Generator in Python2.7 and 3.
# I found this already described in:
# Comprehensions in a class definition mostly cannot access class variable
# [ http://bugs.python.org/issue11796 ]
# ...and my understanding is that this is not going to be fixed.
class Foo1:
def foo(i): return i
bar = (foo(i) for i in range(10))
print(Foo1.bar)
class Foo2:
def foo(i): return i
bar = [foo(i) for i in range(10)]
print(Foo2.bar)
# Results:
#
# $ python2.7 hoge.py
# <generator object <genexpr> at 0xb766b84c>
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#
# $ python3 hoge.py
# <generator object <genexpr> at 0xb75053c4>
# Traceback (most recent call last):
# File "hoge.py", line 6, in <module>
# class Foo2:
# File "hoge.py", line 8, in Foo2
# bar = [foo(i) for i in range(10)]
# File "hoge.py", line 8, in <listcomp>
# bar = [foo(i) for i in range(10)]
# NameError: global name 'foo' is not defined
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment