In Python, is it possible to restrict the type of a function parameter to two possible types?

Viewed 1443

I try to restrict the 'parameter' type to be int or list like the function 'f' below. However, Pycharm does not show a warning at the line f("weewfwef") about wrong parameter type, which means this (parameter : [int, list]) is not correct.

In Python, is it possible to restrict the type of a python function parameter to two possible types?

def f(parameter : [int, list]):
    if len(str(parameter)) <= 3:
        return 3
    else:
        return [1]

if __name__ == '__main__':
    f("weewfwef")

4 Answers

The term you're looking for is a union type.

from typing import Union

def f(parameter: Union[int, list]):
  ...

Union is not limited to two types. If you ever have a value which is one of several known types, but you can't necessarily know which one, you can use Union[...] to encapsulate that information.

Try out typing.Union

from typing import Union
def f(parameter : Union[int,list]):
    if len(str(parameter)) <= 3:
        return 3
    else:
        return [1]

In python, there is no such strict type checking, that's why it follows duck typing https://realpython.com/lessons/duck-typing/

def f(parameter : [int, list]):
    if not(type(parameter) in [list, int]):
        raise ValueError("Invalid Input type")
    if len(str(parameter)) <= 3:
        return 3
    else:
        return [1]
def f(parameter : [int, list]):
    if type(parameter) == (int or list):
        if len(str(parameter)) <= 3:
            return 3
        else:
            return [1]
    else:
        raise ValueError # You can use other error if you want to

if __name__ == '__main__':
    print(f("weewfwef"))

use type() to check it's type and use if statement and raise an error

Related