Home What are list comprehension scoping rules within a Python class?
Reply: 0

What are list comprehension scoping rules within a Python class?

user2039
1#
user2039 Published in July 22, 2018, 8:33 am

This question already has an answer here:

  • Accessing class variables from a list comprehension in the class definition 2 answers

In the following code, the mc assigment works fine in Python 2 and 3.

The cc assignment, which uses the same list comprehension within a class, works in Python 2 but fails with Python 3.

What explains this behavior?

ml1 = "a b c".split()
ml2 = "1 2 3".split()
mc = [ i1 + i2 for i1 in ml1 for i2 in ml2 ]

class Foo(object):
    cl1 = ml1
    cl2 = ml2

    cc1 = [ i1 for i1 in cl1 ]
    cc2 = [ i2 for i2 in cl2 ]
    cc = [ i1 + i2 for i1 in cl1 for i2 in cl2 ]


print("mc = ", mc)
foo = Foo()
print("cc = ", foo.cc)

I get this:

(default-3.5) snafu$ python2 /tmp/z.py 
('mc = ', ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3'])
('cc = ', ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3'])

(default-3.5) snafu$ python3 /tmp/z.py 
Traceback (most recent call last):
  File "/tmp/z.py", line 5, in <module>
    class Foo(object):
  File "/tmp/z.py", line 11, in Foo
    cc = [ i1 + i2 for i1 in cl1 for i2 in cl2 ]
  File "/tmp/z.py", line 11, in <listcomp>
    cc = [ i1 + i2 for i1 in cl1 for i2 in cl2 ]
NameError: name 'cl2' is not defined

Why is the class variable cl2 not defined? Note that the cc2 assignment works fine, as does cc1. Swapping cl1 and cl2 in the comprehension shows that the second loop is the one that triggers the exception, not cl2 per se.)

Versions:

(default-3.5) snafu$ python2 --version
Python 2.7.11+
(default-3.5) snafu$ python3 --version
Python 3.5.1+
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.398187 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO