[Python-Dev] Enum Eccentricities
Guido van Rossum
guido at python.org
Mon Sep 23 17:49:28 CEST 2013
On Mon, Sep 23, 2013 at 8:16 AM, Steven D'Aprano <steve at pearwood.info>wrote:
> On Mon, Sep 23, 2013 at 07:53:00AM -0700, Guido van Rossum wrote:
> > there is no rule that because you can
> > access something on the class you should be able to access it on the
> > instance. Try asking an instance for its class's __mro__ or __bases__.
> It might not be a rule, but it's certainly the norm. I reckon that class
> attributes that aren't accessible from the instance are significantly
> more surprising than Color.red.blue.
Whether this feels right (to me) depends on whether the class attribute was
*meant* to be used as an instance attribute as well, or not. For methods,
that's an obvious yes. For class attributes used as defaults for instance
variables, yes again. For class attributes that are meant to be per-class
state rather than per-instance state, I would use the class name or
__class__ to make it clear to the (human) reader that we're using a class
variable. This also avoids accidentally overriding it with an instance
variable (although that's not an issue for Enum).
> I know I'm in a minority here, but Color.red.blue seems obvious and
> straightforward to me. The fact that it doesn't work surprises me. Given
> instance = Color.red
> assert isinstance(instance, Color) # well of course it is
> assert hasattr(Color, "blue")
> I would expect instance.blue to work, and I'm completely at a loss as to
> how Enum has managed to prevent it.
Through the magic of metaclasses. :-)
The only attributes that an enum instance should have are things like .name
and .value, and the methods implementing various standard protocols like
__repr__ and __eq__.
The whole point of Enum is that it involves a fair bit of magic to offer a
robust way to define Enums that "feel right" as Enums. You shouldn't think
of it as a slightly odd class. You should think of it as a different data
type altogether that happens to be implemented using metaclass tecnology.
But many things you "know" about classes don't apply to Enums; this is just
one of many.
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-Dev