[Python-Dev] PEP 520: Ordered Class Definition Namespace
Ethan Furman
ethan at stoneleaf.us
Tue Jun 7 21:20:38 EDT 2016
On 06/07/2016 05:50 PM, Eric Snow wrote:
Overall +1. Some nits below.
> Specification
> =============
> 3. types for which `__prepare__()`` returned something other than
> ``OrderedDict`` (or a subclass) have their ``__definition_order__``
> set to ``None``
(unless ``__definition_order__`` is present in
the class dict either by virtue of being in the class body or
because the metaclass inserted it before calling
``type.__new__``)
> __definition_order__ = tuple(k for k in locals()
> if (!k.startswith('__') or
> !k.endswith('__')))
Still mixing C and Python! ;)
> Why a tuple?
> ------------
>
> Use of a tuple reflects the fact that we are exposing the order in
> which attributes on the class were *defined*. Since the definition
> is already complete by the time ``definition_order__`` is set, the
> content and order of the value won't be changing. Thus we use a type
> that communicates that state of immutability.
> Why a read-only attribute?
> --------------------------
>
> As with the use of tuple, making ``__definition_order__`` a read-only
> attribute communicates the fact that the information it represents is
> complete. Since it represents the state of a particular one-time event
> (execution of the class definition body), allowing the value to be
> replaced would reduce confidence that the attribute corresponds to the
> original class body.
>
> If a use case for a writable (or mutable) ``__definition_order__``
> arises, the restriction may be loosened later. Presently this seems
> unlikely and furthermore it is usually best to go immutable-by-default.
If __definition_order__ is supposed to be immutable as well as read-only
then we should convert non-tuples to tuples. No point in letting that
user bug slip through.
> Why ignore "dunder" names?
> --------------------------
>
> Names starting and ending with "__" are reserved for use by the
> interpreter. In practice they should not be relevant to the users of
> ``__definition_order__``. Instead, for early everyone they would only
s/early/nearly
> Why is __definition_order__ even necessary?
> -------------------------------------------
>
> Since the definition order is not preserved in ``__dict__``, it would be
> lost once class definition execution completes. Classes *could*
> explicitly set the attribute as the last thing in the body. However,
> then independent decorators could only make use of classes that had done
> so. Instead, ``__definition_order__`` preserves this one bit of info
> from the class body so that it is universally available.
s/would be/is
--
~Ethan~
More information about the Python-Dev
mailing list