[Python-Dev] PEP 520: Ordered Class Definition Namespace
ericsnowcurrently at gmail.com
Tue Jun 7 23:17:16 EDT 2016
On Tue, Jun 7, 2016 at 6:20 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 06/07/2016 05:50 PM, Eric Snow wrote:
>> __definition_order__ = tuple(k for k in locals()
>> if (!k.startswith('__') or
> Still mixing C and Python! ;)
I knew I was missing something!
>> 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.
Do you mean if a class explicitly defines __definition_order__? If
so, I'm not clear on how that would work. It could be set to
anything, including None or a value that does not iterate into a
definition order. If someone explicitly set __definition_order__ then
I think it should be used as-is.
>> 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
>> 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
More information about the Python-Dev