[Python-Dev] PEP 435 - ref impl disc 2

Nick Coghlan ncoghlan at gmail.com
Mon May 6 04:14:58 CEST 2013


On Mon, May 6, 2013 at 8:57 AM, Glenn Linderman <v+python at g.nevcal.com> wrote:
> So you asked why would I want to put a named object as the value of
> something else with a name... maybe Enum should make provision for that...
> if the primary type ( Int for IntEnum, NamedInt for NamedIntEnum) happens to
> have a __name__ property, maybe the name of enumeration members should be
> passed to the constructor for the members... in other words,
>
> class NIE( NamedInt, Enum ):
>         x = 1
>         y = 2
>
> could construct enumeration members x and y whose values are NamedInt('x',
> 1) and
> NamedInt('y', 2)...

I think there comes a point where "subclass the metaclass" is the
right answer to "how do I do X with this type?". I believe making two
different kinds of value labelling mechanisms play nice is such a case
:)

Abstract Base Classes were the first real example of metaclass magic
in the standard library, and they avoided many of the confusing
aspects of metaclass magic by banning instantiation - once you get to
a concrete subclass, instances behave pretty much like any other
instance, even though type(type(obj)) is abc.ABCMeta rather than type:

>>> import collections
>>> class Example(collections.Hashable):
...     def __hash__(self): return 0
...
>>> type(Example)
<class 'abc.ABCMeta'>
>>> type(Example())
<class '__main__.Example'>
>>> type(type(Example()))
<class 'abc.ABCMeta'>

Enumerations will only be the second standard library instance of
using metaclasses to create classes and objects that behave
substantially differently from conventional ones that use type as the
metaclass. The difference in this case relative to ABCs is that more
of the behavioural changes are visible on the instances.

This is *not* a bad thing (this is exactly what the metaclass
machinery is designed to enable), but it does mean we're going to have
to up our game in terms of documenting some of the consequences (as
Ethan noted, this doesn't need to go into the PEP, since that's aimed
at convincing people like Guido that already understand this stuff -
it's the enum module documentation, and potentially the language
reference, that is going to need enhancement). "Here's the section on
metaclasses in the language reference, figure out the consequences for
yourselves" is a defensible situation when we're providing metaclasses
primarily as a toolkit for third party frameworks, but a standard
library module that exploits them the way the enum module does places
additional obligations on us. The upside is that the very presence of
the enum module provides a concrete non-trivial example for us to lean
on in those explanations, rather than having to come up with toy
examples :)

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list