Simple single dispatch.
| 707 | |
| 708 | |
| 709 | class Dispatch: |
| 710 | """Simple single dispatch.""" |
| 711 | |
| 712 | def __init__(self, name=None): |
| 713 | self._lookup = {} |
| 714 | self._lazy = {} |
| 715 | if name: |
| 716 | self.__name__ = name |
| 717 | |
| 718 | def register(self, type, func=None): |
| 719 | """Register dispatch of `func` on arguments of type `type`""" |
| 720 | |
| 721 | def wrapper(func): |
| 722 | if isinstance(type, tuple): |
| 723 | for t in type: |
| 724 | self.register(t, func) |
| 725 | else: |
| 726 | self._lookup[type] = func |
| 727 | return func |
| 728 | |
| 729 | return wrapper(func) if func is not None else wrapper |
| 730 | |
| 731 | def register_lazy(self, toplevel, func=None): |
| 732 | """ |
| 733 | Register a registration function which will be called if the |
| 734 | *toplevel* module (e.g. 'pandas') is ever loaded. |
| 735 | """ |
| 736 | |
| 737 | def wrapper(func): |
| 738 | self._lazy[toplevel] = func |
| 739 | return func |
| 740 | |
| 741 | return wrapper(func) if func is not None else wrapper |
| 742 | |
| 743 | def dispatch(self, cls): |
| 744 | """Return the function implementation for the given ``cls``""" |
| 745 | lk = self._lookup |
| 746 | if cls in lk: |
| 747 | return lk[cls] |
| 748 | for cls2 in cls.__mro__: |
| 749 | # Is a lazy registration function present? |
| 750 | try: |
| 751 | toplevel, _, _ = cls2.__module__.partition(".") |
| 752 | except Exception: |
| 753 | continue |
| 754 | try: |
| 755 | register = self._lazy[toplevel] |
| 756 | except KeyError: |
| 757 | pass |
| 758 | else: |
| 759 | register() |
| 760 | self._lazy.pop(toplevel, None) |
| 761 | meth = self.dispatch(cls) # recurse |
| 762 | lk[cls] = meth |
| 763 | lk[cls2] = meth |
| 764 | return meth |
| 765 | try: |
| 766 | impl = lk[cls2] |
no outgoing calls