100 Days of Code: Day 55
Notes of 100 Days of Code: The Complete Python Pro Bootcamp.
The *args syntax allows a function to accept any number of positional arguments, which are collected into a tuple, while **kwargs allows it to accept any number of keyword arguments (key=value), which are collected into a dictionary.
When talking about omitting *args and **kwargs specifically in a Python decorator’s inner wrapper function, the rules are very strict because of the way the wrapper replaces the original function.
You can only ignore *args and **kwargs in a decorative function if you are absolutely certain that every single function you apply that decorator to takes zero arguments.
Because it’s usually impossible to guarantee that all future functions will be arg-less, the standard best practice for writing reusable decorators is to always include *args and **kwargs in the inner wrapper’s signature.
This makes the wrapper universal, guaranteeing it can intercept and forward any arguments, whether there are zero or twenty.
# This is the robust way:
def universal_decorator(func):
def wrapper(*args, **kwargs): # Included for universality
# ... pre-logic runs here...
# Passes EVERYTHING it received to the original function
result = func(*args, **kwargs)
# ... post-logic runs here...
return result
return wrapper
In the context of decorators, ignoring *args and **kwargs is almost always considered an anti-pattern unless the decorator is purpose-built for a specific zero-argument function.