[Python-ideas] Decorator to avoid a mistake

Guido van Rossum guido at python.org
Mon Nov 28 13:22:43 EST 2016


On Mon, Nov 28, 2016 at 10:11 AM, Chris Barker <chris.barker at noaa.gov>
wrote:

> Am I missing something?
>
> Given Python's dynamic nature, there is simply no way to know if a method
> is overriding a superclass' method until it is called -- and, now that I
> think about it even then you don't know.
>
> At compile time, none of the superclasses may have the given method.
>
> At run time, a method could be monkey patched into the superclass before
> the subclass' instance is created.
>
> In fact, at run time, the superclass could get the method added after
> instances are created.
>
> At calling time, the subclass' method will be found, and used, and the
> search stops there -- no way to know if there is one with the same name
> further up the MRO.
>
> This is simply incompatable with a language this dynamic.
>

Not so fast! Python is also so dynamic that you can easily create a
metaclass (or a class decorator) that does the checking (assuming
reasonable behavior of all classes involved) at class definition time.
Given that the use of such a metaclass will be voluntary, for classes with
unreasonable behavior it should simply not be applied.

I'm not sure yet if it is desirable to have such a metaclass or class
decorator in the stdlib, nor have I thought through its design. Such a
design should first be deployed via PyPI and then we can judge its
effectiveness based on how popular it becomes. (There may already be one,
I've not done that research either.)

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161128/1fc86b57/attachment.html>


More information about the Python-ideas mailing list