core.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from __future__ import annotations
  2. from typing import Any
  3. import inspect
  4. from .dispatcher import Dispatcher, MethodDispatcher, ambiguity_warn
  5. # XXX: This parameter to dispatch isn't documented and isn't used anywhere in
  6. # sympy. Maybe it should just be removed.
  7. global_namespace: dict[str, Any] = {}
  8. def dispatch(*types, namespace=global_namespace, on_ambiguity=ambiguity_warn):
  9. """ Dispatch function on the types of the inputs
  10. Supports dispatch on all non-keyword arguments.
  11. Collects implementations based on the function name. Ignores namespaces.
  12. If ambiguous type signatures occur a warning is raised when the function is
  13. defined suggesting the additional method to break the ambiguity.
  14. Examples
  15. --------
  16. >>> from sympy.multipledispatch import dispatch
  17. >>> @dispatch(int)
  18. ... def f(x):
  19. ... return x + 1
  20. >>> @dispatch(float)
  21. ... def f(x): # noqa: F811
  22. ... return x - 1
  23. >>> f(3)
  24. 4
  25. >>> f(3.0)
  26. 2.0
  27. Specify an isolated namespace with the namespace keyword argument
  28. >>> my_namespace = dict()
  29. >>> @dispatch(int, namespace=my_namespace)
  30. ... def foo(x):
  31. ... return x + 1
  32. Dispatch on instance methods within classes
  33. >>> class MyClass(object):
  34. ... @dispatch(list)
  35. ... def __init__(self, data):
  36. ... self.data = data
  37. ... @dispatch(int)
  38. ... def __init__(self, datum): # noqa: F811
  39. ... self.data = [datum]
  40. """
  41. types = tuple(types)
  42. def _(func):
  43. name = func.__name__
  44. if ismethod(func):
  45. dispatcher = inspect.currentframe().f_back.f_locals.get(
  46. name,
  47. MethodDispatcher(name))
  48. else:
  49. if name not in namespace:
  50. namespace[name] = Dispatcher(name)
  51. dispatcher = namespace[name]
  52. dispatcher.add(types, func, on_ambiguity=on_ambiguity)
  53. return dispatcher
  54. return _
  55. def ismethod(func):
  56. """ Is func a method?
  57. Note that this has to work as the method is defined but before the class is
  58. defined. At this stage methods look like functions.
  59. """
  60. signature = inspect.signature(func)
  61. return signature.parameters.get('self', None) is not None