This PEP proposes class decorators, an extension to the functionand method decorators introduced inPEP 318.
When function decorators were originally debated for inclusion inPython 2.4, class decorators were seen asobscure and unnecessarythanks to metaclasses. After several years’ experiencewith the Python 2.4.x series of releases and an increasingfamiliarity with function decorators and their uses, the BDFL andthe community re-evaluated class decorators and recommended theirinclusion in Python 3.0[1].
The motivating use-case was to make certain constructs more easilyexpressed and less reliant on implementation details of the CPythoninterpreter. While it is possible to express class decorator-likefunctionality using metaclasses, the results are generallyunpleasant and the implementation highly fragile[2]. Inaddition, metaclasses are inherited, whereas class decorators are not,making metaclasses unsuitable for some, single class-specific uses ofclass decorators. The fact that large-scale Python projects like Zopewere going through these wild contortions to achieve something likeclass decorators won over the BDFL.
The semantics and design goals of class decorators are the same asfor function decorators (PEP 318,PEP 318);the onlydifference is that you’re decorating a class instead of a function.The following two snippets are semantically identical:
classA:passA=foo(bar(A))@foo@barclassA:pass
For a detailed examination of decorators, please refer toPEP 318.
Adapting Python’s grammar to support class decorators requiresmodifying two rules and adding a new rule:
funcdef:[decorators]'def'NAMEparameters['->'test]':'suitecompound_stmt:if_stmt|while_stmt|for_stmt|try_stmt|with_stmt|funcdef|classdef
need to be changed to
decorated:decorators(classdef|funcdef)funcdef:'def'NAMEparameters['->'test]':'suitecompound_stmt:if_stmt|while_stmt|for_stmt|try_stmt|with_stmt|funcdef|classdef|decorated
Addingdecorated is necessary to avoid an ambiguity in thegrammar.
The Python AST and bytecode must be modified accordingly.
A reference implementation[3] has been provided byJack Diederich.
There was virtually no discussion following the posting of this PEP,meaning that everyone agreed it should be accepted.
The patch was committed to Subversion as revision 55430.
This document has been placed in the public domain.
Source:https://github.com/python/peps/blob/main/peps/pep-3129.rst
Last modified:2025-02-01 08:59:27 GMT