Polymorphic functions in python
Ad-hoc polymorphism is not supported in python programming language, maybe because weak type checking or something else, but many times I need to have ability to call a function in more than one way. So I should get arguments via **kwargs and implement a switch case like code to handle them.
This code implements the type of polymorphism that I need usually:
import inspect
def polymorphic(fn):
@wraps(fn)
def decorated_view(self, *args, **kwargs):
functions = fn(self, *args, **kwargs)
for function in functions:
args = set(inspect.getargspec(function).args)
if 'self' in args:
args.remove('self')
if args.issubset(set(kwargs.keys())):
return function(self, **kwargs)
return None
return decorated_view
class MyClass(object):
@polymorphic
def __init__(self, *args, **kwargs):
def by_pk(self, pk):
self.load_with_pk(pk)
def by_name(self, name):
self.load_with_name(name)
return [by_pk, by_name]

