Guest User

Untitled

a guest
Mar 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. def _suspend_self(namespace, suspended):
  2. """
  3. Suspends a function, so that it has a self.
  4.  
  5. :param namespace: The self namespace to use.
  6. :return: A function that will call the next function with self.
  7. """
  8.  
  9. def suspender(*args, **kwargs):
  10. return suspended(namespace, *args, **kwargs)
  11.  
  12. suspender.__name__ = suspended.__name__
  13. suspender.__defaults__ = suspended.__defaults__
  14. suspender.__signature__ = getattr(suspended, "__signature__", None)
  15. return suspender
  16.  
  17.  
  18. def make_class(locals: dict):
  19. """
  20. Makes a class, from the locals of the callee.
  21.  
  22. :param locals: The locals to build the class from.
  23. """
  24.  
  25. # try and find a `__call__` to implement the call function
  26. # this is made as a function so that namespace and called can refer to eachother
  27. def call_maker():
  28. if '__call__' in locals and callable(locals['__call__']):
  29. return _suspend_self(namespace, locals['__call__'])
  30.  
  31. def _not_callable(*args, **kwargs):
  32. raise TypeError('This is not callable')
  33.  
  34. return _not_callable
  35.  
  36. # this acts as the "self" object
  37. # all attributes are set on this
  38. def namespace():
  39. return called()
  40.  
  41. # get the callable function that namespace delegates to
  42. # this is called afterwards so that call_maker has the chance to load namespace from cellvars
  43. called = call_maker()
  44.  
  45. # make an init substitute function
  46. def new_class(*args, **kwargs):
  47. init = locals.get("__init__")
  48. if init is not None:
  49. init(namespace, *args, **kwargs)
  50.  
  51. return namespace
  52.  
  53. # update namespace
  54. for name, item in locals.items():
  55. if callable(item):
  56. fn = _suspend_self(namespace, item)
  57. setattr(namespace, name, fn)
  58.  
  59. return new_class
  60.  
  61.  
  62. def make(fn):
  63. """
  64. Makes a class from a function. Example usage:
  65.  
  66. .. code-block:: python
  67.  
  68. from noclasses import make_class, make
  69.  
  70. @make
  71. def MyClass():
  72. def __init__(self, first, second):
  73. self.first = first
  74. self.second = second
  75.  
  76. def add(self):
  77. return self.first + self.second
  78.  
  79. return make_class(locals())
  80.  
  81. instance = MyClass(2, 2)
  82. print(instance.add()) # 4
  83.  
  84. """
  85. return fn()
Add Comment
Please, Sign In to add comment