How do Python decorators work internally? #14999
Answered
by
krishanu717
isthatpratham
asked this question in
Q&A
Replies: 1 comment
|
A decorator is simply a callable that takes a function as input and returns a new function. When you use the @decorator syntax above a function definition, Python executes function = decorator(function) immediately at definition time. The internal process relies on closures. The decorator defines an inner wrapper function that encloses the original function. Because of Python's lexical scoping, this wrapper retains access to the original function object even after the decorator function has finished executing. This allows the wrapper to call the original function later when the decorated function is invoked. |
0 replies
Answer selected by
isthatpratham
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A decorator is simply a callable that takes a function as input and returns a new function. When you use the @decorator syntax above a function definition, Python executes function = decorator(function) immediately at definition time.
The internal process relies on closures. The decorator defines an inner wrapper function that encloses the original function. Because of Python's lexical scoping, this wrapper retains access to the original function object even after the decorator function has finished executing. This allows the wrapper to call the original function later when the decorated function is invoked.