[Python-ideas] PEP 447: Adding type.__getdescriptor__

Nick Coghlan ncoghlan at gmail.com
Fri Dec 1 01:01:11 EST 2017


On 1 December 2017 at 01:23, Ronald Oussoren <ronaldoussoren at mac.com> wrote:
> 1) Last time around Mark Shannon worried that this introduces infinite
> recursion in the language itself (in my crummy summary, please read this
> message to get the real concern
> <https://mail.python.org/pipermail/python-dev/2015-July/140938.html>).  Is
> this truly a problem?  I don’t think there is a problem, but I’m worried
> that I don’t fully understand Mark’s concerns.
>
> 2) PEP 487 introduced __init_subclass__ as a class method to avoid having to
> write a metaclass for a number of use cases.  My PEP currently does require
> a metaclass, but it might be nicer to switch to a regular class method
> instead (like __init_subclass__).

I think the second point there may actually allow you to resolve the
first one, by way of making `__getdescriptor__` an optional override
of the typical lookup algorithm. That is:

    def _PyType_Lookup(tp, name):

        # New optional override for descriptor lookups
        try:
            # Ordinary attribute lookup, *NOT* a descriptor lookup
            getdesc = tp.__getdescriptor__
        except AttributeError:
            pass
        else:
            return getdesc(name)

        # Default algorithm used in the absence of an override
        mro = tp.mro()
        assert isinstance(mro, tuple)

        for base in mro:
           assert isinstance(base, type)

           try:
               return base.__dict__[name]
           except KeyError:
               pass

        return None

If you did go this way, then we'd want to add a
"types.getdescriptor(cls, name)" API to expose _PyType_Lookup at the
Python layer, since "getattr(type(obj), name)" wouldn't be an accurate
emulation of the algorithm any more.

Cheers,
Nick.

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


More information about the Python-ideas mailing list