Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify type that can be either integer or string [duplicate]

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?

like image 302
Ramin-RX7 Avatar asked Mar 06 '26 14:03

Ramin-RX7


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

like image 164
HitLuca Avatar answered Mar 08 '26 19:03

HitLuca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!