Ensure unwanted names removed in class definition

Jussi Piitulainen ei at kun.ei.invalid
Wed Aug 12 18:33:00 CEST 2015


Ben Finney writes:

> How can I ensure incidental names don't end up in the class
> definition, with code that works on both Python 2 and Python 3?
>
> With the following class definition, the incidental names `foo` and
> `bar`, only needed for the list comprehension, remain in the `Parrot`
> namespace::
>
>     __metaclass__ = object
>
>     class Parrot:
>         """ A parrot with beautiful plumage. """
>
>         plumage = [
>                 (foo, bar) for (foo, bar) in feathers.items()
>                 if bar == "beautiful"]
>
>     assert hasattr(Parrot, 'plumage')  # ← okay, has the wanted name
>     assert not hasattr(Parrot, 'foo')  # ← FAILS, has an unwanted name
>     assert not hasattr(Parrot, 'bar')  # ← FAILS, has an unwanted name
[- -]
> How can I write the class definition with the list comprehension and
> *not* keep the incidental names — in code that will run correctly on
> both Python 2 and Python 3?

Make them an implementation detail:

    plumage = [
        (__foo__, __bar__) for (__foo__, __bar__) in feathers.items()
        if __bar__ == "beautiful" ]


More information about the Python-list mailing list