On Tue, Jan 13, 2015 at 7:25 AM, John Ladasky <john_lada...@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)] ... >>> dis.dis(f) 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) 18 GET_ITER 19 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 22 RETURN_VALUE 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. ChrisA -- https://mail.python.org/mailman/listinfo/python-list