Apart from @staticmethod
and @classmethod
? Most languages have some basic libraries making use of most of the language features.
It seems that many of the decorators I find myself making are things which tons of people would use, but I haven't found any inbuilt python decorators which do them. Are there such things?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
Python has two built-in decorators. The staticmethod decorator modifies a method function so that it does not use the self variable. The method function will not have access to a specific instance of the class.
Two decorators ( classmethod() and staticmethod() ) have been available in Python since version 2.2. It's been assumed since approximately that time that some syntactic support for them would eventually be added to the language.
When to Use a Decorator in Python. You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on.
property is usually used as a decorator.
functools has several functions normally used as a decorator, such as total_ordering
, update_wrapped
, lru_cache
, and wraps
.
contextlib has the contextmanager
decorator.
Keep in mind, you can use any function as a decorator:
@decorator
def function(): pass
is just the same as
def function(): pass
function = decorator(function)
In order to be useful, they generally need to be expecting a callable as an argument and they need to return a callable object. (property
is an exception to the second part of that.)
Classes can also be decorated, in exactly the same way.
There is also a list of decorators on the Python Wiki. Some of them are in the standard library, some are not.
property
functools.total_ordering
functools.lru_cache
functools.wraps
contextlib.contextmanager
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With