Why doesn't a dictionary work in classes?

eryk sun eryksun at gmail.com
Tue Dec 25 16:03:04 EST 2018

On 12/25/18, אורי <uri at speedy.net> wrote:
> (it throws an exception: `NameError: name 'GENDERS_DICT' is not defined`)

Python 3 comprehensions have their own scope. This prevents the side
effect of defining the comprehension's loop variable in the enclosing
scope, which is a problem in Python 2. However, it also prevents the
evaluated expression from directly accessing names defined in an
unoptimized enclosing scope, except for the global scope, since such
scopes cannot be the source scope of closure variables. This applies
to comprehensions in class statements and exec(), where globals and
locals are different dicts.

Our 'parameter' for this comprehension scope is the expression for the
outer loop iterable, which gets evaluated in the enclosing scope.
Thus, for what it's worth, we can hack this to work as follows:

    ALL_GENDERS = [GD[gender]
                    for GD, GVV in ((GENDERS_DICT, GENDER_VALID_VALUES),)
                        for gender in GVV]

More information about the Python-list mailing list