Namespace puzzle, list comprehension fails within class definition
rosuav at gmail.com
Mon Jan 12 21:51:23 CET 2015
On Tue, Jan 13, 2015 at 7:25 AM, John Ladasky
<john_ladasky at sbcglobal.net> wrote:
> When I am working inside the class namespace, the print function call on line 8 recognizes the name f and prints the dictionary bound to that name.
> However, the LIST COMPREHENSION defined inside the class namespace generates a NameError.
A list comp is defined with a function call:
>>> def f():
... return [x*x for x in range(4)]
2 0 LOAD_CONST 1 (<code object <listcomp> at
0x7fdf25981420, file "<stdin>", line 2>)
3 LOAD_CONST 2 ('f.<locals>.<listcomp>')
6 MAKE_FUNCTION 0
9 LOAD_GLOBAL 0 (range)
12 LOAD_CONST 3 (4)
15 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
19 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
This prevents leakage of the iterator into the enclosing scope.
Personally, I think it's a hack to get around the fact that Python
doesn't have any concept of sub-function-scope (similar to the weird
hack in try/except); if it weren't for that, true nesting would be
easier. As it is, function definitions in class scope have a special
meaning, and that interferes a bit with list comps.
More information about the Python-list