Python - what are all the built-in decorators?

33,974

Solution 1

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.

Solution 2

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.

Solution 3

Decorators aren't even required to return a function. I've used @atexit.register before.

Share:
33,974
ryeguy
Author by

ryeguy

Updated on January 05, 2020

Comments

  • ryeguy
    ryeguy over 4 years

    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?

  • Benjamin Peterson
    Benjamin Peterson over 15 years
    Well, that one returns the same function passed to it for that very purpose.
  • habnabit
    habnabit over 15 years
    Oh, does it? I never noticed.
  • Dan Burton
    Dan Burton over 13 years
    "Decorators aren't even required to return a function" - in order to make any sense, though, they should, since @decor is just sugar for f = decor(f) - otherwise you will lose the reference to the function you are decorating.
  • habnabit
    habnabit over 13 years
    @Dan, you're aware that @property doesn't return a function, yes?
  • Uncle Dino
    Uncle Dino over 8 years
    Becouse f=decor(f), the function decor need to return something. If you want to call f after the decoration, it need to be a function, if not, it can be anything.
  • habnabit
    habnabit over 8 years
    @Sasszem, every function returns something. If nothing else, you'll at least get None. Either way, there are many non-function callable objects.
  • Peter Schorn
    Peter Schorn about 4 years
    His question was about builtin decorators specifically. There has to be a finite (and probably relatively small) list of builtin decorators.