m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.2 KiB

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