[Python-ideas] PEP 572 version 2: Statement-Local Name Bindings
Nick Coghlan
ncoghlan at gmail.com
Sat Mar 24 22:08:08 EDT 2018
On 25 March 2018 at 02:34, Eric Fahlgren <ericfahlgren at gmail.com> wrote:
> On Sat, Mar 24, 2018 at 7:14 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>
>>
>> >>> class C:
>> ... sequence = range(10)
>> ... listcomp = [x for x in sequence]
>>
>
> >>> class C:
> ... y = 1
> ... sequence = range(10)
> ... listcomp = [x+y for x in sequence]
> ...
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 4, in C
> File "<stdin>", line 4, in <listcomp>
> NameError: name 'y' is not defined
>
> Ok, so how does 'y' fit into these scoping rules?
>
Everything except the outermost iterator is evaluated in the implicitly
nested scope, so comprehensions at class scope have the restriction that
only the outermost iterator can access names defined in the class scope. It
turned out that was enough to preserve compatibility with most of the
comprehensions that folks actually use at class scope.
For those rare cares where it isn't, the typical resolution is to either
define a helper function, or else switch to a regular for loop.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180325/90a2f45a/attachment-0001.html>
More information about the Python-ideas
mailing list