Does Python have decorators in the standard library?

余生长醉 提交于 2020-01-01 07:39:10

问题


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?


回答1:


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.




回答2:


  • property
  • functools.total_ordering
  • functools.lru_cache
  • functools.wraps
  • contextlib.contextmanager

    ...




回答3:


NOt a library per se but a compilation of useful decorators are on http://wiki.python.org/moin/PythonDecoratorLibrary




回答4:


Python decorators are just plain functions or other callables which take as single argument the function or class to be decorated. As such you can use many ordinary functions as decorators and vice versa. Possible use as decorator is often not explicitly documented.



来源:https://stackoverflow.com/questions/7120342/does-python-have-decorators-in-the-standard-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!