Skip to content

Instantly share code, notes, and snippets.

@xkstein
Last active November 9, 2022 18:15
Show Gist options
  • Select an option

  • Save xkstein/f7f7cb8dd3b02722df5fc264cdba731b to your computer and use it in GitHub Desktop.

Select an option

Save xkstein/f7f7cb8dd3b02722df5fc264cdba731b to your computer and use it in GitHub Desktop.
Python Function Overloading With MetaClasses (Terrible)
'''Script that impliments function overloading in python hatefully
Requires python 3.10, doesn't support kwargs for overloaded functions
'''
from inspect import get_annotations
class DispatchDict(dict):
def __call__(self, *args, **kwargs):
if len(self) == 1:
# Hack for non-multiple dispatch functions
return next(iter(self.values()))(self, *args, **kwargs)
if kwargs:
raise NotImplementedError('Add kwargs')
call = tuple([type(arg) for arg in args])
if call not in self:
raise TypeError('Incorrect Args, maybe?')
return self[call](self, *args)
class SetDispatchDict(dict):
def __setitem__(self, key, value):
if callable(value):
dispatch = self.get(key, DispatchDict())
dispatch[tuple(get_annotations(value).values())] = value
value = dispatch
super().__setitem__(key, value)
class DispatchMeta(type):
@classmethod
def __prepare__(cls, name, bases):
return SetDispatchDict()
class Foo(metaclass=DispatchMeta):
def what(self, a: int):
print('int')
def what(self, a: float):
print('float')
def what(self, a: int, b: int):
print('int, int')
def other_func(self, a):
print(f'Single Dispatch with keyword arg: {a}')
if __name__ == '__main__':
f = Foo()
f.what(10)
f.what(10.0)
f.what(10, 10)
f.other_func(a = 'Bupity')
'''Output
int
float
int, int
Single Dispatch with keyword arg: Bupity
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment