Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have decorators in the standard library?

Tags:

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?

like image 808
Li Haoyi Avatar asked Aug 19 '11 10:08

Li Haoyi


People also ask

Did Python use decorators?

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.

What are the inbuilt decorators in Python?

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.

When were decorators added to Python?

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.

Where are decorators used in Python?

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.


2 Answers

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.

like image 60
agf Avatar answered Sep 20 '22 14:09

agf


  • property

  • functools.total_ordering

  • functools.lru_cache

  • functools.wraps

  • contextlib.contextmanager

    ...

like image 33
mouad Avatar answered Sep 24 '22 14:09

mouad