scope of generators, class variables, resulting in global na

b3ng0 phoghawk at gmail.com
Wed Feb 24 10:40:55 EST 2010


On Feb 24, 5:52 am, Nomen Nescio <nob... at dizum.com> wrote:
> Hello,
>
> Can someone help me understand what is wrong with this example?
>
> class T:
>   A = range(2)
>   B = range(4)
>   s = sum(i*j for i in A for j in B)
>
> It produces the exception:
>
> <type 'exceptions.NameError'>: global name 'j' is not defined
>
> The exception above is especially confusing since the following similar example (I just replaced the generator by an explicit array) works:
>
> class T:
>   A = range(2)
>   B = range(4)
>   s = sum([(i*j) for i in A for j in B])
>
> (BTW, the class scope declarations are intentional).
>
> Thanks, Leo.

The best way to mimic the same behavior, while getting around the
scoping issues, would be as follows:

class T:
    A = range(2)
    B = range(4)

    @property
    def s(self):
        return sum(i*j for i in self.A for j in self.B)

T().s will now return 6



More information about the Python-list mailing list