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?
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.
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.
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.
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.
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.
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.
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