On 25 March 2018 at 02:34, Eric Fahlgren <[email protected]> wrote:
> On Sat, Mar 24, 2018 at 7:14 AM, Nick Coghlan <[email protected]> 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 | [email protected] | Brisbane, Australia
_______________________________________________ Python-ideas mailing list [email protected] https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
