Skip to content

Instantly share code, notes, and snippets.

@impiaaa
Created December 2, 2017 00:37
Show Gist options
  • Save impiaaa/4e7656a6dd6595e0e18d58fe2726cab1 to your computer and use it in GitHub Desktop.
Save impiaaa/4e7656a6dd6595e0e18d58fe2726cab1 to your computer and use it in GitHub Desktop.
Python 3 function arithmetic
from arithmetic import *
@arithmetic
def foo(thing):
print(greeting, thing, "!")
foo()
foo("world")
foo.greeting = "Hello"
foo.greeting
foo()
foo("world")
@arithmetic
def bar(thing):
print("Goodbye", thing)
bar()
foo += bar
foo("additional function")
foo = 3*foo
foo("multiplication")
@arithmetic
def baz():
return "composition"
foo *= baz
foo()
from types import FunctionType
class arithmetic(object):
def __init__(self, func):
self._func = func
def __call__(self, *args, **kwargs):
return self._func(*args, **kwargs)
def __add__(self, other):
def f(*args, **kwargs):
self._func(*args, **kwargs)
return other._func(*args, **kwargs)
return __class__(f)
def __mul__(self, other):
def f(*args, **kwargs):
return self._func(other._func(*args, **kwargs))
return __class__(f)
def __setattr__(self, key, val):
if key.startswith('_'):
super().__setattr__(key, val)
else:
self._func = FunctionType(self._func.__code__,
{**self._func.__globals__, key: val},
self._func.__name__,
self._func.__defaults__,
self._func.__closure__)
def __getattr__(self, key):
try:
return getattr(super(), key)
except AttributeError:
if key in self._func.__globals__:
return self._func.__globals__[key]
else:
raise
def __rmul__(self, seq):
if not hasattr(seq, "__iter__"): seq = range(seq)
def f(*args, **kwargs):
return [self._func(*args, **kwargs) for item in seq]
return __class__(f)
__all__ = ["arithmetic"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment