Advertisement
Guest User

FuncBuilder

a guest
Dec 26th, 2011
557
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. '''
  2. Function generator with operator calls
  3.  
  4. >>> f = FuncBuilder()
  5. >>> g = f ** 2
  6. >>> g(10)
  7. 100
  8. >>> g
  9. <var [('pow', 2)]>
  10. >>> g + 1
  11. <var [('pow', 2), ('add', 1)]>
  12. >>> g = f + f
  13. >>> g(1)(2)
  14. 3
  15. >>> g(1, 2)
  16. 3
  17.  
  18. '''
  19.  
  20. import operator
  21.  
  22. class MetaFuncBuilder(type):
  23.     def __init__(self, *args, **kw):
  24.         super().__init__(*args, **kw)
  25.         attr = '__{0}{1}__'
  26.  
  27.         for op in (x for x in dir(operator) if not x.startswith('__')):
  28.  
  29.             oper = getattr(operator, op)
  30.             op = op.rstrip('_') #special case for keywords: and_, or_
  31.  
  32.             def func(self, *n, oper=oper):
  33.                 return type(self)(lambda x: oper(self.func(x), *n),
  34.                                   self.op + [(oper.__name__, n[0])
  35.                                              if n else oper.__name__])
  36.  
  37.             def rfunc(self, n, *, oper=oper):
  38.                 return type(self)(lambda x: oper(n, self.func(x)),
  39.                                   self.op + [(n, oper.__name__)])
  40.            
  41.             setattr(self, attr.format('', op), func)
  42.             setattr(self, attr.format('r', op), rfunc)
  43.  
  44. class FuncBuilder(metaclass=MetaFuncBuilder):
  45.     def __init__(self, func=None, op=None):
  46.         self.op = op if op else []
  47.         self.func = func if func else lambda x: x
  48.  
  49.     def __repr__(self):
  50.         return '<var %s>' % self.op
  51.  
  52.     def __call__(self, *args):
  53.         if not args:
  54.             return self.func() #unary operators
  55.        
  56.         required, *args = args
  57.         out = self.func(required)
  58.         return out(*args) if args else out
  59.  
  60. f = FuncBuilder()
  61.  
  62. # Now play with the function f
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement