Master Python Decorators: From Basics to Advanced Usage
This article provides a comprehensive guide to Python functions, scopes, variable lifecycles, closures, and decorators, illustrating each concept with clear explanations and runnable code examples, and shows how to create flexible, reusable decorators using @ syntax, *args, and **kwargs.
Functions
In Python, a function is defined with the def keyword, a name, optional parameters, and a return statement. Example:
def foo():
return 1
foo() # returns 1Scope
Each function creates a new local namespace. Variables are first looked up in the local scope, then in enclosing scopes, and finally in the global scope.
a_string = "This is a global variable"
def foo():
print(locals())
# prints {}
foo()Variable Resolution Rules
Python searches the current scope for a variable; if not found, it moves outward to enclosing scopes. Modifying a global variable inside a function without global creates a new local variable that hides the global one.
a_string = "global"
def foo():
a_string = "local"
print(a_string) # prints "local"
foo()
print(a_string) # prints "global"Variable Lifecycle
Variables defined inside a function exist only for the duration of that function call. Accessing them after the function returns raises NameError.
def foo():
x = 1
foo()
print(x) # NameErrorFunction Parameters
Functions can have positional parameters, default (named) parameters, and can be called with various argument styles.
def foo(x, y=0):
return x - y
foo(3, 1) # returns 2
foo(3) # returns 3
foo(y=1, x=3) # returns 2Nested Functions
Python allows defining functions inside other functions. The inner function can access variables from the enclosing (non‑global) scope.
def outer():
x = 1
def inner():
print(x)
inner()
outer() # prints 1Functions as First‑Class Objects
Functions are objects; they can be passed as arguments, returned from other functions, and stored in variables.
def add(x, y):
return x + y
def sub(x, y):
return x - y
def apply(func, x, y):
return func(x, y)
apply(add, 2, 1) # returns 3
apply(sub, 2, 1) # returns 1Closures
A closure captures variables from its defining environment. The captured variables persist even after the outer function has finished executing.
def outer(x):
def inner():
print(x)
return inner
f1 = outer(1)
f2 = outer(2)
f1() # prints 1
f2() # prints 2Decorators
A decorator is a higher‑order function that takes a function, wraps additional behavior around it, and returns a new function.
def outer(some_func):
def inner():
print("before some_func")
ret = some_func()
return ret + 1
return inner
def foo():
return 1
decorated = outer(foo)
print(decorated()) # prints "before some_func" and returns 2Using the @ Syntax
Python 2.4+ allows applying a decorator with the @ symbol placed above a function definition.
@wrapper
def add(a, b):
return Coordinate(a.x + b.x, a.y + b.y)*args and **kwargs
The *args syntax collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary.
def one(*args):
print(args)
one(1, 2, 3) # prints (1, 2, 3)
def two(x, y, *args):
print(x, y, args)
two('a', 'b', 'c') # prints a b ('c',)
def foo(**kwargs):
print(kwargs)
foo(x=1, y=2) # prints {'x': 1, 'y': 2}General‑Purpose Decorator Example
A logger decorator can record any function’s arguments before invoking it.
def logger(func):
def inner(*args, **kwargs):
print("Arguments were: %s, %s" % (args, kwargs))
return func(*args, **kwargs)
return inner
@logger
def foo1(x, y=1):
return x * y
@logger
def foo2():
return 2
foo1(5, 4) # logs arguments and returns 20
foo1(1) # logs arguments and returns 1
foo2() # logs arguments and returns 2This tutorial demonstrates how Python’s functional features—functions, scopes, closures, and decorators—enable clean, reusable code patterns.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
