[Python-Dev] PEP520 and absence of __definition_order__

Ethan Furman ethan at stoneleaf.us
Sat Sep 10 03:49:43 EDT 2016


Per Victor's advice I'm posting this here.

PEP 520 has been accepted, but without the __definition_order__ attribute.
The accompanying comment:

> "Note: Since compact dict has landed in 3.6, __definition_order__ has
> been removed. cls.__dict__ now mostly accomplishes the same thing
> instead."

The "mostly" is what concerns me.  Much like having a custom __dir__ lets
a class fine-tune what is of interest, a custom __definition_order__ allows
a class to present a unified view of the class creation process.  This could
be important to classes that employ __getattr__ (or __getattribute__) to
provide virtual attributes, such as Enum or proxy classes.

With __definition_order__ Enum can display the actual creation order of enum
members and methods, while relying on Enum.__dict__.keys() presents a jumbled
mess with many attributes the user never wrote, the enum members either
appearing /after/ all the methods (even if actually written before), or
entirely absent.

For example,  this class:

>>> class PassBy(Enum):
...     value = 1
...     reference = 2
...     name = 3
...     object = name
...     def used_by_python(self):
...         return self.name == 'name'
...

shows this:

>>> PassBy.__dict__.keys()
dict_keys([
    '_generate_next_value_',
     '__module__',
     'used_by_python',
    '__doc__',
     '_member_names_',
     '_member_map_',
     '_member_type_',
     '_value2member_map_',
     'reference',
     'object',
     '__new__',
    ])

Notice that two of the members are missing, and all are after the method.

If __definition_order__ existed it would be this:

>>> PassBy.__definition_order__
['value', 'reference', 'name', 'object', 'used_by_python']

Which is a much more accurate picture of the user's class.

--
~Ethan~


More information about the Python-Dev mailing list