Namespace puzzle, list comprehension fails within class definition

Ethan Furman ethan at stoneleaf.us
Mon Jan 12 21:40:13 CET 2015


On 01/12/2015 12:25 PM, John Ladasky wrote:
> d = {0:"a", 1:"b", 2:"c", 3:"d"}
> e = [d[x] for x in (0,2)]
> 
> class Foo:
>     f = {0:"a", 1:"b", 2:"c", 3:"d"}
>     print(f)
>     g = [f[x] for x in (0,2)]

In Foo 'f' is part of an unnamed namespace; the list comp 'g' has its own namespace, effectively making be a nonlocal;
class name lookup skips nonlocal namespaces.

Workaround:  use an actual for loop.

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20150112/925a1e3f/attachment.sig>


More information about the Python-list mailing list