Overload function in python

Here is how you can fake overloading a function in python.

_REGISTER = {}

def overload(fn):
  num_args = len(inspect.getfullargspec(fn).args)
  _REGISTER[fn.__name__, num_args] = fn

  def dispatcher(*args, **kwargs):
    actual = _REGISTER[fn.__name__, len(args)]
    return actual(*args, **kwargs)

  return dispatcher


@overload
def f(one):
  print("f1", one)

@overload
def f(one, two):
  print("f2", one, two)


@overload
def g(one):
  print("g1", one)

@overload
def g(one, two):
  print("g2", one, two)
  


f(1)
f(2, 3)
g(4)
g(5, 6)

Links