Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #83632
| References | <af9bb2fd-f0b9-4efb-874e-78f30ac65b7e@googlegroups.com> |
|---|---|
| Date | 2015-01-13 07:51 +1100 |
| Subject | Re: Namespace puzzle, list comprehension fails within class definition |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.17639.1421095890.18130.python-list@python.org> (permalink) |
On Tue, Jan 13, 2015 at 7:25 AM, John Ladasky
<john_ladasky@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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Namespace puzzle, list comprehension fails within class definition John Ladasky <john_ladasky@sbcglobal.net> - 2015-01-12 12:25 -0800
Re: Namespace puzzle, list comprehension fails within class definition Ethan Furman <ethan@stoneleaf.us> - 2015-01-12 12:40 -0800
Re: Namespace puzzle, list comprehension fails within class definition John Ladasky <john_ladasky@sbcglobal.net> - 2015-01-12 12:49 -0800
Re: Namespace puzzle, list comprehension fails within class definition Steven D'Aprano <steve@pearwood.info> - 2015-01-13 04:49 +0000
Re: Namespace puzzle, list comprehension fails within class definition Ethan Furman <ethan@stoneleaf.us> - 2015-01-12 22:00 -0800
Re: Namespace puzzle, list comprehension fails within class definition John Ladasky <john_ladasky@sbcglobal.net> - 2015-01-12 12:43 -0800
Re: Namespace puzzle, list comprehension fails within class definition Chris Angelico <rosuav@gmail.com> - 2015-01-13 07:51 +1100
csiph-web