Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Decorators

Decorator expressions are evaluated at definition time from top to bottom and applied from bottom to top.

Version: Python 3.14; repository image, production runtime not attested

Syntax

@outer
@inner
def work():
    return 3

Decorator expressions are evaluated at definition time from top to bottom and applied from bottom to top.

The name binds to the outer decorator's result, so calls can enter a wrapper first. wraps copies selected metadata and sets __wrapped__ while the wrapper still handles calls.

Inner B surrounds x, outer A surrounds BxB, producing ABxBA. The retained name is label.

events=[]
def make(tag):
    events.append('make'+tag)
    def decorate(f):
        events.append('apply'+tag)
        return f
    return decorate
@make('A')
@make('B')
def sample(): pass
assert events==['makeA','makeB','applyB','applyA']

Examples

from functools import wraps

def surround(tag):
    def decorate(fn):
        @wraps(fn)
        def wrapped(*args, **kwargs):
            return tag + fn(*args, **kwargs) + tag
        return wrapped
    return decorate

@surround("A")
@surround("B")
def label(value):
    return value

print(label("x"), label.__name__)

Result

ABxBA label

Inner B surrounds x, outer A surrounds BxB, producing ABxBA. The retained name is label.

Sources