[Python-Dev] Enum Eccentricities

Ethan Furman ethan at stoneleaf.us
Mon Sep 23 18:12:27 CEST 2013


On 09/23/2013 08:16 AM, Steven D'Aprano wrote:
>
> I would expect instance.blue to work, and I'm completely at a loss as to
> how Enum has managed to prevent it.

[A peek behind the curtains...]

Currently, Enum members do not live in the class dict.  So when, for example, blue is searched for in red, it is not 
found in the instance dict, and it is not found in the class dict.  As you know, __getattr__ will then be invoked -- but 
the Enum class does not have its own __getattr__, nor its own __getattribute__, and so we get an AttributeError.

Well, you may ask, if blue does not live in the class dict, how does Color.blue work?  I'm glad you asked.  ;)

Color is of type EnumMeta, and EnumMeta /does/ have __getattr__, so a failed /class/ lookup will invoke the metaclass 
__getattr__, which will search in the right place, find, and return, Color.blue.

--
~Ethan~


More information about the Python-Dev mailing list