Home > Enterprise >  Python function overloading recommended approach
Python function overloading recommended approach

Time:06-08

Assume a function that takes an object as parameter. There could be various ways to express the parameter object creation, some of which expressive, and likely easier to be used.

To give a simple example, we have a function which takes DateTime. We also want to accept string representations of DateTime, if possible (for example '20220606').

# version 1, strict. must send a DateTime  
def UsefulFunc(startdate: DateTime) -> None:
    pass

# version 2, allow more types, but loose on type hints
def UsefulFunc(startdate: (DateTime, str)) -> None:
    # check if type is str, convert to DateTime if yes
    pass

# version 3, multiple signatures to accept and call the base function 
def UsefulFuncString(startdatestr: str) -> None:
    # convert startdatestr to DateTime
    UsefulFunc(startdate)

# … …

What approach is recommended in Python (I come from C# background)? If there's no clear indication/ or decision is based on situation, what are the considerations?

CodePudding user response:

if you want type hint your function, you can use typing.Union

from datetime import datetime
from typing import Union
def UsefulFunc(startdate:Union[str, datetime]) -> None
    ...

or in py3.10

def UsefulFunc(startdate:str|datetime) -> None
    ...

but type hint are just decoration in python, if you want to do something base on those types you need to check inside your function and work accordingly

 def UsefulFunc(startdate:str|datetime) -> None
    if isinstance(startdate,str):
        ...
    elif isinstance(startdate,datetime): 
        ...
    else:
        raise ValueError("Invalid type")

There is also the functools.singledispatch that help you do the above for you

from functools import singledispatch

@singledispatch
def UsefulFunc(startdate):
    ... #else case

@UsefulFunc.register
def _(startdate:datetime):
    ... #datetime case

@UsefulFunc.register
def _(startdate:str):
    ... #str case
  • Related