decorator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. """Useful utility decorators. """
  2. from typing import TypeVar
  3. import sys
  4. import types
  5. import inspect
  6. from functools import wraps, update_wrapper
  7. from sympy.utilities.exceptions import sympy_deprecation_warning
  8. T = TypeVar('T')
  9. """A generic type"""
  10. def threaded_factory(func, use_add):
  11. """A factory for ``threaded`` decorators. """
  12. from sympy.core import sympify
  13. from sympy.matrices import MatrixBase
  14. from sympy.utilities.iterables import iterable
  15. @wraps(func)
  16. def threaded_func(expr, *args, **kwargs):
  17. if isinstance(expr, MatrixBase):
  18. return expr.applyfunc(lambda f: func(f, *args, **kwargs))
  19. elif iterable(expr):
  20. try:
  21. return expr.__class__([func(f, *args, **kwargs) for f in expr])
  22. except TypeError:
  23. return expr
  24. else:
  25. expr = sympify(expr)
  26. if use_add and expr.is_Add:
  27. return expr.__class__(*[ func(f, *args, **kwargs) for f in expr.args ])
  28. elif expr.is_Relational:
  29. return expr.__class__(func(expr.lhs, *args, **kwargs),
  30. func(expr.rhs, *args, **kwargs))
  31. else:
  32. return func(expr, *args, **kwargs)
  33. return threaded_func
  34. def threaded(func):
  35. """Apply ``func`` to sub--elements of an object, including :class:`~.Add`.
  36. This decorator is intended to make it uniformly possible to apply a
  37. function to all elements of composite objects, e.g. matrices, lists, tuples
  38. and other iterable containers, or just expressions.
  39. This version of :func:`threaded` decorator allows threading over
  40. elements of :class:`~.Add` class. If this behavior is not desirable
  41. use :func:`xthreaded` decorator.
  42. Functions using this decorator must have the following signature::
  43. @threaded
  44. def function(expr, *args, **kwargs):
  45. """
  46. return threaded_factory(func, True)
  47. def xthreaded(func):
  48. """Apply ``func`` to sub--elements of an object, excluding :class:`~.Add`.
  49. This decorator is intended to make it uniformly possible to apply a
  50. function to all elements of composite objects, e.g. matrices, lists, tuples
  51. and other iterable containers, or just expressions.
  52. This version of :func:`threaded` decorator disallows threading over
  53. elements of :class:`~.Add` class. If this behavior is not desirable
  54. use :func:`threaded` decorator.
  55. Functions using this decorator must have the following signature::
  56. @xthreaded
  57. def function(expr, *args, **kwargs):
  58. """
  59. return threaded_factory(func, False)
  60. def conserve_mpmath_dps(func):
  61. """After the function finishes, resets the value of ``mpmath.mp.dps`` to
  62. the value it had before the function was run."""
  63. import mpmath
  64. def func_wrapper(*args, **kwargs):
  65. dps = mpmath.mp.dps
  66. try:
  67. return func(*args, **kwargs)
  68. finally:
  69. mpmath.mp.dps = dps
  70. func_wrapper = update_wrapper(func_wrapper, func)
  71. return func_wrapper
  72. class no_attrs_in_subclass:
  73. """Don't 'inherit' certain attributes from a base class
  74. >>> from sympy.utilities.decorator import no_attrs_in_subclass
  75. >>> class A(object):
  76. ... x = 'test'
  77. >>> A.x = no_attrs_in_subclass(A, A.x)
  78. >>> class B(A):
  79. ... pass
  80. >>> hasattr(A, 'x')
  81. True
  82. >>> hasattr(B, 'x')
  83. False
  84. """
  85. def __init__(self, cls, f):
  86. self.cls = cls
  87. self.f = f
  88. def __get__(self, instance, owner=None):
  89. if owner == self.cls:
  90. if hasattr(self.f, '__get__'):
  91. return self.f.__get__(instance, owner)
  92. return self.f
  93. raise AttributeError
  94. def doctest_depends_on(exe=None, modules=None, disable_viewers=None,
  95. python_version=None, ground_types=None):
  96. """
  97. Adds metadata about the dependencies which need to be met for doctesting
  98. the docstrings of the decorated objects.
  99. ``exe`` should be a list of executables
  100. ``modules`` should be a list of modules
  101. ``disable_viewers`` should be a list of viewers for :func:`~sympy.printing.preview.preview` to disable
  102. ``python_version`` should be the minimum Python version required, as a tuple
  103. (like ``(3, 0)``)
  104. """
  105. dependencies = {}
  106. if exe is not None:
  107. dependencies['executables'] = exe
  108. if modules is not None:
  109. dependencies['modules'] = modules
  110. if disable_viewers is not None:
  111. dependencies['disable_viewers'] = disable_viewers
  112. if python_version is not None:
  113. dependencies['python_version'] = python_version
  114. if ground_types is not None:
  115. dependencies['ground_types'] = ground_types
  116. def skiptests():
  117. from sympy.testing.runtests import DependencyError, SymPyDocTests, PyTestReporter # lazy import
  118. r = PyTestReporter()
  119. t = SymPyDocTests(r, None)
  120. try:
  121. t._check_dependencies(**dependencies)
  122. except DependencyError:
  123. return True # Skip doctests
  124. else:
  125. return False # Run doctests
  126. def depends_on_deco(fn):
  127. fn._doctest_depends_on = dependencies
  128. fn.__doctest_skip__ = skiptests
  129. if inspect.isclass(fn):
  130. fn._doctest_depdends_on = no_attrs_in_subclass(
  131. fn, fn._doctest_depends_on)
  132. fn.__doctest_skip__ = no_attrs_in_subclass(
  133. fn, fn.__doctest_skip__)
  134. return fn
  135. return depends_on_deco
  136. def public(obj: T) -> T:
  137. """
  138. Append ``obj``'s name to global ``__all__`` variable (call site).
  139. By using this decorator on functions or classes you achieve the same goal
  140. as by filling ``__all__`` variables manually, you just do not have to repeat
  141. yourself (object's name). You also know if object is public at definition
  142. site, not at some random location (where ``__all__`` was set).
  143. Note that in multiple decorator setup (in almost all cases) ``@public``
  144. decorator must be applied before any other decorators, because it relies
  145. on the pointer to object's global namespace. If you apply other decorators
  146. first, ``@public`` may end up modifying the wrong namespace.
  147. Examples
  148. ========
  149. >>> from sympy.utilities.decorator import public
  150. >>> __all__ # noqa: F821
  151. Traceback (most recent call last):
  152. ...
  153. NameError: name '__all__' is not defined
  154. >>> @public
  155. ... def some_function():
  156. ... pass
  157. >>> __all__ # noqa: F821
  158. ['some_function']
  159. """
  160. if isinstance(obj, types.FunctionType):
  161. ns = obj.__globals__
  162. name = obj.__name__
  163. elif isinstance(obj, (type(type), type)):
  164. ns = sys.modules[obj.__module__].__dict__
  165. name = obj.__name__
  166. else:
  167. raise TypeError("expected a function or a class, got %s" % obj)
  168. if "__all__" not in ns:
  169. ns["__all__"] = [name]
  170. else:
  171. ns["__all__"].append(name)
  172. return obj
  173. def memoize_property(propfunc):
  174. """Property decorator that caches the value of potentially expensive
  175. ``propfunc`` after the first evaluation. The cached value is stored in
  176. the corresponding property name with an attached underscore."""
  177. attrname = '_' + propfunc.__name__
  178. sentinel = object()
  179. @wraps(propfunc)
  180. def accessor(self):
  181. val = getattr(self, attrname, sentinel)
  182. if val is sentinel:
  183. val = propfunc(self)
  184. setattr(self, attrname, val)
  185. return val
  186. return property(accessor)
  187. def deprecated(message, *, deprecated_since_version,
  188. active_deprecations_target, stacklevel=3):
  189. '''
  190. Mark a function as deprecated.
  191. This decorator should be used if an entire function or class is
  192. deprecated. If only a certain functionality is deprecated, you should use
  193. :func:`~.warns_deprecated_sympy` directly. This decorator is just a
  194. convenience. There is no functional difference between using this
  195. decorator and calling ``warns_deprecated_sympy()`` at the top of the
  196. function.
  197. The decorator takes the same arguments as
  198. :func:`~.warns_deprecated_sympy`. See its
  199. documentation for details on what the keywords to this decorator do.
  200. See the :ref:`deprecation-policy` document for details on when and how
  201. things should be deprecated in SymPy.
  202. Examples
  203. ========
  204. >>> from sympy.utilities.decorator import deprecated
  205. >>> from sympy import simplify
  206. >>> @deprecated("""\
  207. ... The simplify_this(expr) function is deprecated. Use simplify(expr)
  208. ... instead.""", deprecated_since_version="1.1",
  209. ... active_deprecations_target='simplify-this-deprecation')
  210. ... def simplify_this(expr):
  211. ... """
  212. ... Simplify ``expr``.
  213. ...
  214. ... .. deprecated:: 1.1
  215. ...
  216. ... The ``simplify_this`` function is deprecated. Use :func:`simplify`
  217. ... instead. See its documentation for more information. See
  218. ... :ref:`simplify-this-deprecation` for details.
  219. ...
  220. ... """
  221. ... return simplify(expr)
  222. >>> from sympy.abc import x
  223. >>> simplify_this(x*(x + 1) - x**2) # doctest: +SKIP
  224. <stdin>:1: SymPyDeprecationWarning:
  225. <BLANKLINE>
  226. The simplify_this(expr) function is deprecated. Use simplify(expr)
  227. instead.
  228. <BLANKLINE>
  229. See https://docs.sympy.org/latest/explanation/active-deprecations.html#simplify-this-deprecation
  230. for details.
  231. <BLANKLINE>
  232. This has been deprecated since SymPy version 1.1. It
  233. will be removed in a future version of SymPy.
  234. <BLANKLINE>
  235. simplify_this(x)
  236. x
  237. See Also
  238. ========
  239. sympy.utilities.exceptions.SymPyDeprecationWarning
  240. sympy.utilities.exceptions.sympy_deprecation_warning
  241. sympy.utilities.exceptions.ignore_warnings
  242. sympy.testing.pytest.warns_deprecated_sympy
  243. '''
  244. decorator_kwargs = {"deprecated_since_version": deprecated_since_version,
  245. "active_deprecations_target": active_deprecations_target}
  246. def deprecated_decorator(wrapped):
  247. if hasattr(wrapped, '__mro__'): # wrapped is actually a class
  248. class wrapper(wrapped):
  249. __doc__ = wrapped.__doc__
  250. __module__ = wrapped.__module__
  251. _sympy_deprecated_func = wrapped
  252. if '__new__' in wrapped.__dict__:
  253. def __new__(cls, *args, **kwargs):
  254. sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
  255. return super().__new__(cls, *args, **kwargs)
  256. else:
  257. def __init__(self, *args, **kwargs):
  258. sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
  259. super().__init__(*args, **kwargs)
  260. wrapper.__name__ = wrapped.__name__
  261. else:
  262. @wraps(wrapped)
  263. def wrapper(*args, **kwargs):
  264. sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
  265. return wrapped(*args, **kwargs)
  266. wrapper._sympy_deprecated_func = wrapped
  267. return wrapper
  268. return deprecated_decorator