Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a function parameter accept 2 or more type?

Tags:

python

types

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

like image 559
Kally Avatar asked Feb 14 '26 04:02

Kally


1 Answers

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.

like image 189
Tom Aarsen Avatar answered Feb 16 '26 18:02

Tom Aarsen