Skip to content

Instantly share code, notes, and snippets.

@Foxboron
Created March 2, 2014 04:19
Hacks
'''
Define functions inside functions,
recompile the correct function matching the
arg count and hand it back.
'''
from types import FunctionType
class Multi(object):
def __init__(self, fn):
self.fn = fn
def is_fn(self, fn):
if isinstance(fn, type(self.fn.__code__)):
if fn.co_argcount == len(self.args)+len(self.kwargs.keys()):
if all([kw in fn.co_varnames for kw in self.kwargs.keys()]):
return True
return False
def __call__(self, *args, **kwargs):
ret, self.args, self.kwargs = self.fn, args, kwargs
for i in self.fn.__code__.co_consts:
if self.is_fn(i):
ret = FunctionType(i, globals=globals())
break
return ret(*args,**kwargs)
@Multi
def _a(*args, **kwargs):
def fun1(arg1):
print("hey1")
def fun2(arg1, arg2):
print(arg2)
def fun3(test, arg=None):
raise Exception("lol")
print("fail")
_a() #=> "fail"
_a(1,2) #=> 2
_a(1, arg="Hello") #=> Exception raised "lol"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment