Henning Koehler
Henning Koehler

Reputation: 2657

Overloading functions by type

Since python 3.5 function arguments can be declared with a type, but overloading by argument type doesn't appear to be supported. Specifically I have an old class definition

class Supplies:
    def __init__(self, supp):
        if isinstance(supp, list):
            self.food = supp[0]
            self.water = supp[1]
        else:
            self.food = supp
            self.water = supp

and want to convert the constructor to use type declarations. Something like this:

class Supplies:
    def __init__(self, supp: List[int]):
        self.food = supp[0]
        self.water = supp[1]
    def __init__(self, supp: int):
        self.food = supp
        self.water = supp

except that this overrides rather than overloads __init__. Is there a sensible workaround here (since it's a constructor I cannot simply use two different function names)?

Upvotes: 1

Views: 59

Answers (1)

Henning Koehler
Henning Koehler

Reputation: 2657

Found a solution that exposes the desired interface:

SupplyData = TypeVar('SupplyData', List[int], int)
class Supplies:
    def __init__(self, supp: SupplyData):
        if isinstance(supp, list):
            self.food = supp[0]
            self.water = supp[1]
        else:
            self.food = supp
            self.water = supp

or with anonymous type as suggested in the comment above:

class Supplies:
    def __init__(self, supp: Union[List[int], int]):
        if isinstance(supp, list):
            self.food = supp[0]
            self.water = supp[1]
        else:
            self.food = supp
            self.water = supp

Upvotes: 1

Related Questions