[Python-Dev] PEP 520: Ordered Class Definition Namespace

Nick Coghlan ncoghlan at gmail.com
Fri Jun 10 14:29:09 EDT 2016

On 10 June 2016 at 09:42, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> On Thu, Jun 9, 2016 at 2:39 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> That restriction would be comparable to what we do with __slots__ today:
>>     >>> class C:
>>     ...     __slots__ = 1
>>     ...
>>     Traceback (most recent call last):
>>      File "<stdin>", line 1, in <module>
>>     TypeError: 'int' object is not iterable
> Are you suggesting that we require it be a tuple of identifiers (or
> None) and raise TypeError otherwise, similar to __slots__?  The
> difference is that __slots__ has specific type requirements that do
> not apply to __definition_order__, as well as a different purpose.
> __definition_order__ is about preserving definition-type info that we
> are currently throwing away.

If we don't enforce the tuple-of-identifiers restriction at type
creation time, everyone that *doesn't* make it a tuple-of-identifiers
is likely to have a subtle compatibility bug with class decorators and
other code that assume the default tuple-of-identifiers format is the
only possible format (aside from None). To put it in PEP 484 terms:
regardless of what the PEP says, people are going to assume the type
of __definition_order__ is Optional[Tuple[str]], as that's going to
cover almost all class definitions they encounter.

It makes sense to me to give class definitions and metaclasses the
opportunity to change the *content* of the definition order: "Use
these names in this order, not the names and order you would have
calculated by default".

It doesn't make sense to me to give them an opportunity to change the
*form* of the definition order, since that makes it incredibly
difficult to consume correctly: "Sure, it's *normally* a
tuple-of-identifiers, but it *might* be a dictionary, or a complex
number, or a set, or whatever the class author decided to make it".

By contrast, if the class machinery enforces Optional[Tuple[str]],
then it becomes a lot easier to consume reliably, and anyone violating
the constraint gets an immediate exception when defining the offending
class, rather than a potentially obscure exception from a class
decorator or other piece of code that assumes __definition_order__
could only be None or a tuple of strings.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list