How do you create a function whose arguments accepts 2 or even more data types. I have a Product class as follows
class Product:
def __init__(self, name: str, price: int | float)
self.product = {'name': name, 'price': price)
This results into a TypeError
TypeError: unsupported operand type(s) for |: 'type' and 'type'
Then I try using or operator, but it picks up type int only
How can I make sure that it accepts both int and float
Yes, in typing this is done with Union:
from typing import Union
class Product:
def __init__(self, name: str, price: Union[int, float])
self.product = {'name': name, 'price': price)
Note, as you can read from the documentation, this is possible with int | float, but only from version Python 3.10 onwards. As most users are not yet on Python 3.10, in practice people still tend to use Union[int, float].
However, int | float is preferred if you do not care about supporting versions below Python 3.10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With