operations.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. from __future__ import annotations
  2. from operator import attrgetter
  3. from collections import defaultdict
  4. from sympy.utilities.exceptions import sympy_deprecation_warning
  5. from .sympify import _sympify as _sympify_, sympify
  6. from .basic import Basic
  7. from .cache import cacheit
  8. from .sorting import ordered
  9. from .logic import fuzzy_and
  10. from .parameters import global_parameters
  11. from sympy.utilities.iterables import sift
  12. from sympy.multipledispatch.dispatcher import (Dispatcher,
  13. ambiguity_register_error_ignore_dup,
  14. str_signature, RaiseNotImplementedError)
  15. class AssocOp(Basic):
  16. """ Associative operations, can separate noncommutative and
  17. commutative parts.
  18. (a op b) op c == a op (b op c) == a op b op c.
  19. Base class for Add and Mul.
  20. This is an abstract base class, concrete derived classes must define
  21. the attribute `identity`.
  22. .. deprecated:: 1.7
  23. Using arguments that aren't subclasses of :class:`~.Expr` in core
  24. operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
  25. deprecated. See :ref:`non-expr-args-deprecated` for details.
  26. Parameters
  27. ==========
  28. *args :
  29. Arguments which are operated
  30. evaluate : bool, optional
  31. Evaluate the operation. If not passed, refer to ``global_parameters.evaluate``.
  32. """
  33. # for performance reason, we don't let is_commutative go to assumptions,
  34. # and keep it right here
  35. __slots__: tuple[str, ...] = ('is_commutative',)
  36. _args_type: type[Basic] | None = None
  37. @cacheit
  38. def __new__(cls, *args, evaluate=None, _sympify=True):
  39. # Allow faster processing by passing ``_sympify=False``, if all arguments
  40. # are already sympified.
  41. if _sympify:
  42. args = list(map(_sympify_, args))
  43. # Disallow non-Expr args in Add/Mul
  44. typ = cls._args_type
  45. if typ is not None:
  46. from .relational import Relational
  47. if any(isinstance(arg, Relational) for arg in args):
  48. raise TypeError("Relational cannot be used in %s" % cls.__name__)
  49. # This should raise TypeError once deprecation period is over:
  50. for arg in args:
  51. if not isinstance(arg, typ):
  52. sympy_deprecation_warning(
  53. f"""
  54. Using non-Expr arguments in {cls.__name__} is deprecated (in this case, one of
  55. the arguments has type {type(arg).__name__!r}).
  56. If you really did intend to use a multiplication or addition operation with
  57. this object, use the * or + operator instead.
  58. """,
  59. deprecated_since_version="1.7",
  60. active_deprecations_target="non-expr-args-deprecated",
  61. stacklevel=4,
  62. )
  63. if evaluate is None:
  64. evaluate = global_parameters.evaluate
  65. if not evaluate:
  66. obj = cls._from_args(args)
  67. obj = cls._exec_constructor_postprocessors(obj)
  68. return obj
  69. args = [a for a in args if a is not cls.identity]
  70. if len(args) == 0:
  71. return cls.identity
  72. if len(args) == 1:
  73. return args[0]
  74. c_part, nc_part, order_symbols = cls.flatten(args)
  75. is_commutative = not nc_part
  76. obj = cls._from_args(c_part + nc_part, is_commutative)
  77. obj = cls._exec_constructor_postprocessors(obj)
  78. if order_symbols is not None:
  79. from sympy.series.order import Order
  80. return Order(obj, *order_symbols)
  81. return obj
  82. @classmethod
  83. def _from_args(cls, args, is_commutative=None):
  84. """Create new instance with already-processed args.
  85. If the args are not in canonical order, then a non-canonical
  86. result will be returned, so use with caution. The order of
  87. args may change if the sign of the args is changed."""
  88. if len(args) == 0:
  89. return cls.identity
  90. elif len(args) == 1:
  91. return args[0]
  92. obj = super().__new__(cls, *args)
  93. if is_commutative is None:
  94. is_commutative = fuzzy_and(a.is_commutative for a in args)
  95. obj.is_commutative = is_commutative
  96. return obj
  97. def _new_rawargs(self, *args, reeval=True, **kwargs):
  98. """Create new instance of own class with args exactly as provided by
  99. caller but returning the self class identity if args is empty.
  100. Examples
  101. ========
  102. This is handy when we want to optimize things, e.g.
  103. >>> from sympy import Mul, S
  104. >>> from sympy.abc import x, y
  105. >>> e = Mul(3, x, y)
  106. >>> e.args
  107. (3, x, y)
  108. >>> Mul(*e.args[1:])
  109. x*y
  110. >>> e._new_rawargs(*e.args[1:]) # the same as above, but faster
  111. x*y
  112. Note: use this with caution. There is no checking of arguments at
  113. all. This is best used when you are rebuilding an Add or Mul after
  114. simply removing one or more args. If, for example, modifications,
  115. result in extra 1s being inserted they will show up in the result:
  116. >>> m = (x*y)._new_rawargs(S.One, x); m
  117. 1*x
  118. >>> m == x
  119. False
  120. >>> m.is_Mul
  121. True
  122. Another issue to be aware of is that the commutativity of the result
  123. is based on the commutativity of self. If you are rebuilding the
  124. terms that came from a commutative object then there will be no
  125. problem, but if self was non-commutative then what you are
  126. rebuilding may now be commutative.
  127. Although this routine tries to do as little as possible with the
  128. input, getting the commutativity right is important, so this level
  129. of safety is enforced: commutativity will always be recomputed if
  130. self is non-commutative and kwarg `reeval=False` has not been
  131. passed.
  132. """
  133. if reeval and self.is_commutative is False:
  134. is_commutative = None
  135. else:
  136. is_commutative = self.is_commutative
  137. return self._from_args(args, is_commutative)
  138. @classmethod
  139. def flatten(cls, seq):
  140. """Return seq so that none of the elements are of type `cls`. This is
  141. the vanilla routine that will be used if a class derived from AssocOp
  142. does not define its own flatten routine."""
  143. # apply associativity, no commutativity property is used
  144. new_seq = []
  145. while seq:
  146. o = seq.pop()
  147. if o.__class__ is cls: # classes must match exactly
  148. seq.extend(o.args)
  149. else:
  150. new_seq.append(o)
  151. new_seq.reverse()
  152. # c_part, nc_part, order_symbols
  153. return [], new_seq, None
  154. def _matches_commutative(self, expr, repl_dict=None, old=False):
  155. """
  156. Matches Add/Mul "pattern" to an expression "expr".
  157. repl_dict ... a dictionary of (wild: expression) pairs, that get
  158. returned with the results
  159. This function is the main workhorse for Add/Mul.
  160. Examples
  161. ========
  162. >>> from sympy import symbols, Wild, sin
  163. >>> a = Wild("a")
  164. >>> b = Wild("b")
  165. >>> c = Wild("c")
  166. >>> x, y, z = symbols("x y z")
  167. >>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
  168. {a_: x, b_: y, c_: z}
  169. In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is
  170. the expression.
  171. The repl_dict contains parts that were already matched. For example
  172. here:
  173. >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
  174. {a_: x, b_: y, c_: z}
  175. the only function of the repl_dict is to return it in the
  176. result, e.g. if you omit it:
  177. >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
  178. {b_: y, c_: z}
  179. the "a: x" is not returned in the result, but otherwise it is
  180. equivalent.
  181. """
  182. from .function import _coeff_isneg
  183. # make sure expr is Expr if pattern is Expr
  184. from .expr import Expr
  185. if isinstance(self, Expr) and not isinstance(expr, Expr):
  186. return None
  187. if repl_dict is None:
  188. repl_dict = {}
  189. # handle simple patterns
  190. if self == expr:
  191. return repl_dict
  192. d = self._matches_simple(expr, repl_dict)
  193. if d is not None:
  194. return d
  195. # eliminate exact part from pattern: (2+a+w1+w2).matches(expr) -> (w1+w2).matches(expr-a-2)
  196. from .function import WildFunction
  197. from .symbol import Wild
  198. wild_part, exact_part = sift(self.args, lambda p:
  199. p.has(Wild, WildFunction) and not expr.has(p),
  200. binary=True)
  201. if not exact_part:
  202. wild_part = list(ordered(wild_part))
  203. if self.is_Add:
  204. # in addition to normal ordered keys, impose
  205. # sorting on Muls with leading Number to put
  206. # them in order
  207. wild_part = sorted(wild_part, key=lambda x:
  208. x.args[0] if x.is_Mul and x.args[0].is_Number else
  209. 0)
  210. else:
  211. exact = self._new_rawargs(*exact_part)
  212. free = expr.free_symbols
  213. if free and (exact.free_symbols - free):
  214. # there are symbols in the exact part that are not
  215. # in the expr; but if there are no free symbols, let
  216. # the matching continue
  217. return None
  218. newexpr = self._combine_inverse(expr, exact)
  219. if not old and (expr.is_Add or expr.is_Mul):
  220. check = newexpr
  221. if _coeff_isneg(check):
  222. check = -check
  223. if check.count_ops() > expr.count_ops():
  224. return None
  225. newpattern = self._new_rawargs(*wild_part)
  226. return newpattern.matches(newexpr, repl_dict)
  227. # now to real work ;)
  228. i = 0
  229. saw = set()
  230. while expr not in saw:
  231. saw.add(expr)
  232. args = tuple(ordered(self.make_args(expr)))
  233. if self.is_Add and expr.is_Add:
  234. # in addition to normal ordered keys, impose
  235. # sorting on Muls with leading Number to put
  236. # them in order
  237. args = tuple(sorted(args, key=lambda x:
  238. x.args[0] if x.is_Mul and x.args[0].is_Number else
  239. 0))
  240. expr_list = (self.identity,) + args
  241. for last_op in reversed(expr_list):
  242. for w in reversed(wild_part):
  243. d1 = w.matches(last_op, repl_dict)
  244. if d1 is not None:
  245. d2 = self.xreplace(d1).matches(expr, d1)
  246. if d2 is not None:
  247. return d2
  248. if i == 0:
  249. if self.is_Mul:
  250. # make e**i look like Mul
  251. if expr.is_Pow and expr.exp.is_Integer:
  252. from .mul import Mul
  253. if expr.exp > 0:
  254. expr = Mul(*[expr.base, expr.base**(expr.exp - 1)], evaluate=False)
  255. else:
  256. expr = Mul(*[1/expr.base, expr.base**(expr.exp + 1)], evaluate=False)
  257. i += 1
  258. continue
  259. elif self.is_Add:
  260. # make i*e look like Add
  261. c, e = expr.as_coeff_Mul()
  262. if abs(c) > 1:
  263. from .add import Add
  264. if c > 0:
  265. expr = Add(*[e, (c - 1)*e], evaluate=False)
  266. else:
  267. expr = Add(*[-e, (c + 1)*e], evaluate=False)
  268. i += 1
  269. continue
  270. # try collection on non-Wild symbols
  271. from sympy.simplify.radsimp import collect
  272. was = expr
  273. did = set()
  274. for w in reversed(wild_part):
  275. c, w = w.as_coeff_mul(Wild)
  276. free = c.free_symbols - did
  277. if free:
  278. did.update(free)
  279. expr = collect(expr, free)
  280. if expr != was:
  281. i += 0
  282. continue
  283. break # if we didn't continue, there is nothing more to do
  284. return
  285. def _has_matcher(self):
  286. """Helper for .has() that checks for containment of
  287. subexpressions within an expr by using sets of args
  288. of similar nodes, e.g. x + 1 in x + y + 1 checks
  289. to see that {x, 1} & {x, y, 1} == {x, 1}
  290. """
  291. def _ncsplit(expr):
  292. # this is not the same as args_cnc because here
  293. # we don't assume expr is a Mul -- hence deal with args --
  294. # and always return a set.
  295. cpart, ncpart = sift(expr.args,
  296. lambda arg: arg.is_commutative is True, binary=True)
  297. return set(cpart), ncpart
  298. c, nc = _ncsplit(self)
  299. cls = self.__class__
  300. def is_in(expr):
  301. if isinstance(expr, cls):
  302. if expr == self:
  303. return True
  304. _c, _nc = _ncsplit(expr)
  305. if (c & _c) == c:
  306. if not nc:
  307. return True
  308. elif len(nc) <= len(_nc):
  309. for i in range(len(_nc) - len(nc) + 1):
  310. if _nc[i:i + len(nc)] == nc:
  311. return True
  312. return False
  313. return is_in
  314. def _eval_evalf(self, prec):
  315. """
  316. Evaluate the parts of self that are numbers; if the whole thing
  317. was a number with no functions it would have been evaluated, but
  318. it wasn't so we must judiciously extract the numbers and reconstruct
  319. the object. This is *not* simply replacing numbers with evaluated
  320. numbers. Numbers should be handled in the largest pure-number
  321. expression as possible. So the code below separates ``self`` into
  322. number and non-number parts and evaluates the number parts and
  323. walks the args of the non-number part recursively (doing the same
  324. thing).
  325. """
  326. from .add import Add
  327. from .mul import Mul
  328. from .symbol import Symbol
  329. from .function import AppliedUndef
  330. if isinstance(self, (Mul, Add)):
  331. x, tail = self.as_independent(Symbol, AppliedUndef)
  332. # if x is an AssocOp Function then the _evalf below will
  333. # call _eval_evalf (here) so we must break the recursion
  334. if not (tail is self.identity or
  335. isinstance(x, AssocOp) and x.is_Function or
  336. x is self.identity and isinstance(tail, AssocOp)):
  337. # here, we have a number so we just call to _evalf with prec;
  338. # prec is not the same as n, it is the binary precision so
  339. # that's why we don't call to evalf.
  340. x = x._evalf(prec) if x is not self.identity else self.identity
  341. args = []
  342. tail_args = tuple(self.func.make_args(tail))
  343. for a in tail_args:
  344. # here we call to _eval_evalf since we don't know what we
  345. # are dealing with and all other _eval_evalf routines should
  346. # be doing the same thing (i.e. taking binary prec and
  347. # finding the evalf-able args)
  348. newa = a._eval_evalf(prec)
  349. if newa is None:
  350. args.append(a)
  351. else:
  352. args.append(newa)
  353. return self.func(x, *args)
  354. # this is the same as above, but there were no pure-number args to
  355. # deal with
  356. args = []
  357. for a in self.args:
  358. newa = a._eval_evalf(prec)
  359. if newa is None:
  360. args.append(a)
  361. else:
  362. args.append(newa)
  363. return self.func(*args)
  364. @classmethod
  365. def make_args(cls, expr):
  366. """
  367. Return a sequence of elements `args` such that cls(*args) == expr
  368. Examples
  369. ========
  370. >>> from sympy import Symbol, Mul, Add
  371. >>> x, y = map(Symbol, 'xy')
  372. >>> Mul.make_args(x*y)
  373. (x, y)
  374. >>> Add.make_args(x*y)
  375. (x*y,)
  376. >>> set(Add.make_args(x*y + y)) == set([y, x*y])
  377. True
  378. """
  379. if isinstance(expr, cls):
  380. return expr.args
  381. else:
  382. return (sympify(expr),)
  383. def doit(self, **hints):
  384. if hints.get('deep', True):
  385. terms = [term.doit(**hints) for term in self.args]
  386. else:
  387. terms = self.args
  388. return self.func(*terms, evaluate=True)
  389. class ShortCircuit(Exception):
  390. pass
  391. class LatticeOp(AssocOp):
  392. """
  393. Join/meet operations of an algebraic lattice[1].
  394. Explanation
  395. ===========
  396. These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))),
  397. commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a).
  398. Common examples are AND, OR, Union, Intersection, max or min. They have an
  399. identity element (op(identity, a) = a) and an absorbing element
  400. conventionally called zero (op(zero, a) = zero).
  401. This is an abstract base class, concrete derived classes must declare
  402. attributes zero and identity. All defining properties are then respected.
  403. Examples
  404. ========
  405. >>> from sympy import Integer
  406. >>> from sympy.core.operations import LatticeOp
  407. >>> class my_join(LatticeOp):
  408. ... zero = Integer(0)
  409. ... identity = Integer(1)
  410. >>> my_join(2, 3) == my_join(3, 2)
  411. True
  412. >>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4)
  413. True
  414. >>> my_join(0, 1, 4, 2, 3, 4)
  415. 0
  416. >>> my_join(1, 2)
  417. 2
  418. References
  419. ==========
  420. .. [1] https://en.wikipedia.org/wiki/Lattice_%28order%29
  421. """
  422. is_commutative = True
  423. def __new__(cls, *args, **options):
  424. args = (_sympify_(arg) for arg in args)
  425. try:
  426. # /!\ args is a generator and _new_args_filter
  427. # must be careful to handle as such; this
  428. # is done so short-circuiting can be done
  429. # without having to sympify all values
  430. _args = frozenset(cls._new_args_filter(args))
  431. except ShortCircuit:
  432. return sympify(cls.zero)
  433. if not _args:
  434. return sympify(cls.identity)
  435. elif len(_args) == 1:
  436. return set(_args).pop()
  437. else:
  438. # XXX in almost every other case for __new__, *_args is
  439. # passed along, but the expectation here is for _args
  440. obj = super(AssocOp, cls).__new__(cls, *ordered(_args))
  441. obj._argset = _args
  442. return obj
  443. @classmethod
  444. def _new_args_filter(cls, arg_sequence, call_cls=None):
  445. """Generator filtering args"""
  446. ncls = call_cls or cls
  447. for arg in arg_sequence:
  448. if arg == ncls.zero:
  449. raise ShortCircuit(arg)
  450. elif arg == ncls.identity:
  451. continue
  452. elif arg.func == ncls:
  453. yield from arg.args
  454. else:
  455. yield arg
  456. @classmethod
  457. def make_args(cls, expr):
  458. """
  459. Return a set of args such that cls(*arg_set) == expr.
  460. """
  461. if isinstance(expr, cls):
  462. return expr._argset
  463. else:
  464. return frozenset([sympify(expr)])
  465. @staticmethod
  466. def _compare_pretty(a, b):
  467. return (str(a) > str(b)) - (str(a) < str(b))
  468. class AssocOpDispatcher:
  469. """
  470. Handler dispatcher for associative operators
  471. .. notes::
  472. This approach is experimental, and can be replaced or deleted in the future.
  473. See https://github.com/sympy/sympy/pull/19463.
  474. Explanation
  475. ===========
  476. If arguments of different types are passed, the classes which handle the operation for each type
  477. are collected. Then, a class which performs the operation is selected by recursive binary dispatching.
  478. Dispatching relation can be registered by ``register_handlerclass`` method.
  479. Priority registration is unordered. You cannot make ``A*B`` and ``B*A`` refer to
  480. different handler classes. All logic dealing with the order of arguments must be implemented
  481. in the handler class.
  482. Examples
  483. ========
  484. >>> from sympy import Add, Expr, Symbol
  485. >>> from sympy.core.add import add
  486. >>> class NewExpr(Expr):
  487. ... @property
  488. ... def _add_handler(self):
  489. ... return NewAdd
  490. >>> class NewAdd(NewExpr, Add):
  491. ... pass
  492. >>> add.register_handlerclass((Add, NewAdd), NewAdd)
  493. >>> a, b = Symbol('a'), NewExpr()
  494. >>> add(a, b) == NewAdd(a, b)
  495. True
  496. """
  497. def __init__(self, name, doc=None):
  498. self.name = name
  499. self.doc = doc
  500. self.handlerattr = "_%s_handler" % name
  501. self._handlergetter = attrgetter(self.handlerattr)
  502. self._dispatcher = Dispatcher(name)
  503. def __repr__(self):
  504. return "<dispatched %s>" % self.name
  505. def register_handlerclass(self, classes, typ, on_ambiguity=ambiguity_register_error_ignore_dup):
  506. """
  507. Register the handler class for two classes, in both straight and reversed order.
  508. Paramteters
  509. ===========
  510. classes : tuple of two types
  511. Classes who are compared with each other.
  512. typ:
  513. Class which is registered to represent *cls1* and *cls2*.
  514. Handler method of *self* must be implemented in this class.
  515. """
  516. if not len(classes) == 2:
  517. raise RuntimeError(
  518. "Only binary dispatch is supported, but got %s types: <%s>." % (
  519. len(classes), str_signature(classes)
  520. ))
  521. if len(set(classes)) == 1:
  522. raise RuntimeError(
  523. "Duplicate types <%s> cannot be dispatched." % str_signature(classes)
  524. )
  525. self._dispatcher.add(tuple(classes), typ, on_ambiguity=on_ambiguity)
  526. self._dispatcher.add(tuple(reversed(classes)), typ, on_ambiguity=on_ambiguity)
  527. @cacheit
  528. def __call__(self, *args, _sympify=True, **kwargs):
  529. """
  530. Parameters
  531. ==========
  532. *args :
  533. Arguments which are operated
  534. """
  535. if _sympify:
  536. args = tuple(map(_sympify_, args))
  537. handlers = frozenset(map(self._handlergetter, args))
  538. # no need to sympify again
  539. return self.dispatch(handlers)(*args, _sympify=False, **kwargs)
  540. @cacheit
  541. def dispatch(self, handlers):
  542. """
  543. Select the handler class, and return its handler method.
  544. """
  545. # Quick exit for the case where all handlers are same
  546. if len(handlers) == 1:
  547. h, = handlers
  548. if not isinstance(h, type):
  549. raise RuntimeError("Handler {!r} is not a type.".format(h))
  550. return h
  551. # Recursively select with registered binary priority
  552. for i, typ in enumerate(handlers):
  553. if not isinstance(typ, type):
  554. raise RuntimeError("Handler {!r} is not a type.".format(typ))
  555. if i == 0:
  556. handler = typ
  557. else:
  558. prev_handler = handler
  559. handler = self._dispatcher.dispatch(prev_handler, typ)
  560. if not isinstance(handler, type):
  561. raise RuntimeError(
  562. "Dispatcher for {!r} and {!r} must return a type, but got {!r}".format(
  563. prev_handler, typ, handler
  564. ))
  565. # return handler class
  566. return handler
  567. @property
  568. def __doc__(self):
  569. docs = [
  570. "Multiply dispatched associative operator: %s" % self.name,
  571. "Note that support for this is experimental, see the docs for :class:`AssocOpDispatcher` for details"
  572. ]
  573. if self.doc:
  574. docs.append(self.doc)
  575. s = "Registered handler classes\n"
  576. s += '=' * len(s)
  577. docs.append(s)
  578. amb_sigs = []
  579. typ_sigs = defaultdict(list)
  580. for sigs in self._dispatcher.ordering[::-1]:
  581. key = self._dispatcher.funcs[sigs]
  582. typ_sigs[key].append(sigs)
  583. for typ, sigs in typ_sigs.items():
  584. sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs)
  585. if isinstance(typ, RaiseNotImplementedError):
  586. amb_sigs.append(sigs_str)
  587. continue
  588. s = 'Inputs: %s\n' % sigs_str
  589. s += '-' * len(s) + '\n'
  590. s += typ.__name__
  591. docs.append(s)
  592. if amb_sigs:
  593. s = "Ambiguous handler classes\n"
  594. s += '=' * len(s)
  595. docs.append(s)
  596. s = '\n'.join(amb_sigs)
  597. docs.append(s)
  598. return '\n\n'.join(docs)