Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - what are all the built-in decorators? [closed]

I know of @staticmethod, @classmethod, and @property, but only through scattered documentation. What are all the function decorators that are built into Python? Is that in the docs? Is there an up-to-date list maintained somewhere?

like image 871
ryeguy Avatar asked Jan 26 '09 15:01

ryeguy


People also ask

What are the built in decorators in Python?

Some commonly used decorators that are built into Python are @classmethod , @staticmethod , and @property . The @classmethod and @staticmethod decorators are used to define methods inside a class namespace that's not connected to a particular instance of that class.

Are Python decorators closures?

Decorators are also a powerful tool in Python which are implemented using closures and allow the programmers to modify the behavior of a function without permanently modifying it.

How many types of decorators are there in Python?

In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here. Before we get into the fun details of how a basic decorator works and how to implement your own decorators, let's see why we need them in the first place.

Are Python decorators necessary?

Python is praised for its clear and concise syntax, and decorators are no exceptions. If there is any behaviour that is common to more than one function, you probably need to make a decorator. Here are some examples when they might come in handy: Check arguments type at runtime.


2 Answers

I don't think so. Decorators don't differ from ordinary functions, you only call them in a fancier way.

For finding all of them try searching Built-in functions list, because as you can see in Python glossary the decorator syntax is just a syntactic sugar, as the following two definitions create equal functions (copied this example from glossary):

def f(...):     ... f = staticmethod(f)  @staticmethod def f(...): 

So any built-in function that returns another function can be used as a decorator. Question is - does it make sense to use it that way? :-)

functools module contains some functions that can be used as decorators, but they aren't built-ins you asked for.

like image 125
Abgan Avatar answered Sep 19 '22 13:09

Abgan


They're not built-in, but this library of example decorators is very good.

As Abgan says, the built-in function list is probably the best place to look. Although, since decorators can also be implemented as classes, it's not guaranteed to be comprehensive.

like image 39
James Brady Avatar answered Sep 23 '22 13:09

James Brady