Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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")

like image 832
Tom Avatar asked Oct 14 '22 23:10

Tom


2 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.

like image 52
Silvio Mayolo Avatar answered Nov 15 '22 05:11

Silvio Mayolo


Try out typing.Union

from typing import Union
def f(parameter : Union[int,list]):
    if len(str(parameter)) <= 3:
        return 3
    else:
        return [1]
like image 39
programmer365 Avatar answered Nov 15 '22 04:11

programmer365