Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. from inspect import getfullargspec
  2.  
  3.  
  4. class Function(object):
  5.  
  6.     def __init__(self, fn):
  7.         self.fn = fn
  8.  
  9.     def __call__(self, *args, **kwargs):
  10.         fn = Namespace.get_instance().get(self.fn, *args)
  11.  
  12.         if not fn:
  13.             raise Exception("no matching function found.")
  14.  
  15.         return fn(*args, **kwargs)
  16.  
  17.     def key(self, args=None):
  18.         if args is None:
  19.             args = getfullargspec(self.fn).args
  20.  
  21.         return tuple([
  22.             self.fn.__module__,
  23.             self.fn.__class__,
  24.             self.fn.__name__,
  25.             len(args or []),
  26.         ])
  27.  
  28.  
  29. class Namespace(object):
  30.     __instance = None
  31.  
  32.     def __init__(self):
  33.         if self.__instance is None:
  34.             self.function_map = dict()
  35.             Namespace.__instance = self
  36.         else:
  37.             raise Exception("cannot instantiate a virtual Namespace again")
  38.  
  39.     @staticmethod
  40.     def get_instance():
  41.         if Namespace.__instance is None:
  42.             Namespace()
  43.         return Namespace.__instance
  44.  
  45.     def get(self, fn, *args):
  46.         func = Function(fn)
  47.         return self.function_map.get(func.key(args=args))
  48.  
  49.     def register(self, fn):
  50.         func = Function(fn)
  51.         self.function_map[func.key()] = fn
  52.         return func
  53.  
  54.  
  55. def overload(fn):
  56.     return Namespace.get_instance().register(fn)
  57.  
  58.  
  59. @overload
  60. def foo():
  61.     print(")(")
  62.  
  63.  
  64. @overload
  65. def foo(x):
  66.     print("with arg x")
  67.  
  68.  
  69. def main():
  70.     foo(1)
  71.     foo()
  72.  
  73.  
  74. if __name__ == "__main__":
  75.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement