Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just to add a specific example of a good use from my answer <a href="https://stackoverflow.com/questions/3834263/is-clojures-multi-method-dispatch-truly-superior-say-to-what-i-can-do-in-pytho/3842928#3842928">here</a>, coupled with decorators a simple mechanism for multimethods can be done.</p> <pre><code># This is in the 'mm' module registry = {} import inspect class MultiMethod(object): def __init__(self, name): self.name = name self.typemap = {} def __call__(self, *args): types = tuple(arg.__class__ for arg in args) # a generator expression! function = self.typemap.get(types) if function is None: raise TypeError("no match") return function(*args) def register(self, types, function): if types in self.typemap: raise TypeError("duplicate registration") self.typemap[types] = function def multimethod(function): name = function.__name__ mm = registry.get(name) if mm is None: mm = registry[name] = MultiMethod(name) spec = inspect.getfullargspec(function) types = tuple(spec.annotations[x] for x in spec.args) mm.register(types, function) return mm </code></pre> <p>and an example of use:</p> <pre><code>from mm import multimethod @multimethod def foo(a: int): return "an int" @multimethod def foo(a: int, b: str): return "an int and a string" if __name__ == '__main__': print("foo(1,'a') = {}".format(foo(1,'a'))) print("foo(7) = {}".format(foo(7))) </code></pre> <p>This can be done by adding the types to the decorator as <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=101605" rel="nofollow noreferrer">Guido's original post</a> shows, but annotating the parameters themselves is better as it avoids the possibility of wrong matching of parameters and types.</p> <p><em>Note</em>: In Python you can access the annotations as <code>function.__annotations__</code> rather than <code>function.func_annotations</code> as the <code>func_*</code> style was removed on Python 3.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload