Skip to content

Instantly share code, notes, and snippets.

@lbillingham
Created January 20, 2017 09:30
Show Gist options
  • Save lbillingham/7fa3ef2f9cd3e78d9c41e9f752373fd8 to your computer and use it in GitHub Desktop.
Save lbillingham/7fa3ef2f9cd3e78d9c41e9f752373fd8 to your computer and use it in GitHub Desktop.
python class scope is odd
class Spam(object):
"""
Demo of python class scope
fails
on py 3.5
> `File "class_scope.py", line 20, in <listcomp>`
> `...`
> `NameError: name 'ham_gen_list' is not defined`
on py 2.7
> `File "class_scope.py", line 21, in <genexpr>((i,))`
> `...`
> `NameError: global name 'ham_compre_enum_list' is not defined`
"""
ham = 10
ham_range = range(ham)
ham_list = [x for x in ham_range]
ham_gen_list = list(x for x in ham_list)
ham_compre_enum_list = [ham_gen_list[i] for i in range(ham)]
ham_gen_enum_list = list(ham_compre_enum_list[i] for i in range(ham))
# generators are functions but fail to capture the enclosing scope
# in the same way as named-defined functions
# http://stackoverflow.com/a/13913933/3751373
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment