How to specify type that can be either integer or string

Viewed 5783

I have a function that its parameter should be integer or string.

from typing import int,str

def MyFunc(arg:int) -> None:
    print(arg)

but I want to know how to write it to tell the user arg can be both int and str?

2 Answers

First of all, I don't think you need to use the import as int and str are base types.

Apart from that my solution would be (python3)

from typing import Union

def MyFunc(arg:Union[int, str]) -> None:
    print(arg)

This is the standard approach, that would also allow you to use type checkers like mypy. The Union keyword indicates that your argument can be either one of the types inside the square brackets.

One option is

def MyFunc(arg:"int or str") -> None:
    print(arg)

Another option is

def MyFunc(arg:[int,str]) -> None:
    print(arg)
Related