[Python-ideas] Decorator to avoid a mistake

Nick Coghlan ncoghlan at gmail.com
Tue Nov 29 08:39:38 EST 2016


On 29 November 2016 at 08:01, Chris Barker <chris.barker at noaa.gov> wrote:
> On Mon, Nov 28, 2016 at 1:50 PM, Guido van Rossum <guido at python.org> wrote:
>>>
>>> Also -- the ship has kinda sailed on this - maybe a @not_override would
>>> make more sense.
>>>
>>> Isn't the goal to make sure you don't accidentally override a method?
>>> saying "I know I'm overriding this" is less useful than "I'm not intending
>>> to override anything here"
>>
>> I think you're fighting a straw man. I never said @override should be
>> added to the language. I said that it would be useful to have a 3rd party
>> metaclass or a class decorator that implements it which packages may
>> voluntarily use to constrain their subclasses (or their own uses --
>> different designs are possible).
>
>
> I know -- I just happened to add that to a reply to you...
>
> That was for the OP, or anyone else thinking of writing such a thing.
>
> And I still think it would better be added to a linting tool than at
> run-time -- but let whoever writes it figure that out.

Writing linting tools for Python class hierarchies is pretty hard in
the general case, since you have to account for the fact that the
module level control flow logic is Turing complete (and many linters
simply don't try, instead saying "don't do that if you want the linter
to work properly").

By contrast, a class decorator or metaclass can do the checks at
runtime by walking the MRO, just as ABCMeta can look for
@abstractmethod declarations that haven't been overridden in a
subclass, and SQL Alchemy can map subclass inheritance to table
linkages.

If you look at the way attrs writes its automatic __init__ methods for
example, it creates a single flat __init__ based on the definition
time MRO: https://attrs.readthedocs.io/en/stable/how-does-it-work.html

That's the nice part about this kind of thing being opt-in: the
definition time tooling *doesn't* have to cope with the full extent of
Python's dynamic nature, as it can expect the user to be cooperating
with the tool to some degree, and "you're not cooperating" can be a
valid error to throw.

Cheers,
Nick.

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


More information about the Python-ideas mailing list