def keyword, docstring, arguments, and return.
typeguard module and @typechecked decorator.
*args collects extra positional args into a
tuple, and **kwargs collects extra keyword args into a dictionary.
* or ** to explode a
sequence (list/tuple) or a dictionary into individual function arguments.
* in the parameter list.
Standard -> *args -> Keyword-only -> **kwargs.
__defaults__
and __kwdefaults__ attributes when the code is first loaded.
None instead of []
or {} as default parameters.
power_factory(2) executes, it creates an environment where the variable exp is assigned the
value 2.
power_factory finishes, the returned square function "carries" that environment
(exp=2) with it. This "function-plus-environment" entity is the closure.
.py file); visible throughout the entire file.
len, int, and print.
| Scope | Defined In | Lifetime |
|---|---|---|
| Local (L) | Current function or lambda |
Created at call; destroyed on return |
| Enclosing (E) | Outer / Parent function | Persists as long as the Closure instance exists |
| Global (G) | Top level of the script or module | Until the script ends |
| Built-in (B) | Python Interpreter internals | Always available while Python is running |
global, nonlocalglobal or nonlocal; otherwise, Python will treat the assignment as the creation
of a new L variable.
lambdalambda arguments: expression.
lambda pitfall
@decorator syntax passes only the decorated function (func) to the
decorator. If you write @timer_decorator("Log"), Python first executes
timer_decorator("Log") and expects it to return the actual decorator.
| Method | Code | Feature |
|---|---|---|
| Decorator | @my_decorator |
simple, elegant, readable |
| Assignment | my_func = my_decorator(my_func) |
shows the decorator's underlying logic, function reassignment |
@dataclass
is designed to decorate classes.
locals(), globals(),
hasattr(), and dir(), isinstance(), issubclass(), etc.
Note: Python has a default recursion step limit, you can check and modify it as above.