Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Function generator with operator calls
- >>> f = FuncBuilder()
- >>> g = f ** 2
- >>> g(10)
- 100
- >>> g
- <var [('pow', 2)]>
- >>> g + 1
- <var [('pow', 2), ('add', 1)]>
- >>> g = f + f
- >>> g(1)(2)
- 3
- >>> g(1, 2)
- 3
- '''
- import operator
- class MetaFuncBuilder(type):
- def __init__(self, *args, **kw):
- super().__init__(*args, **kw)
- attr = '__{0}{1}__'
- for op in (x for x in dir(operator) if not x.startswith('__')):
- oper = getattr(operator, op)
- op = op.rstrip('_') #special case for keywords: and_, or_
- def func(self, *n, oper=oper):
- return type(self)(lambda x: oper(self.func(x), *n),
- self.op + [(oper.__name__, n[0])
- if n else oper.__name__])
- def rfunc(self, n, *, oper=oper):
- return type(self)(lambda x: oper(n, self.func(x)),
- self.op + [(n, oper.__name__)])
- setattr(self, attr.format('', op), func)
- setattr(self, attr.format('r', op), rfunc)
- class FuncBuilder(metaclass=MetaFuncBuilder):
- def __init__(self, func=None, op=None):
- self.op = op if op else []
- self.func = func if func else lambda x: x
- def __repr__(self):
- return '<var %s>' % self.op
- def __call__(self, *args):
- if not args:
- return self.func() #unary operators
- required, *args = args
- out = self.func(required)
- return out(*args) if args else out
- f = FuncBuilder()
- # Now play with the function f
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement