Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I make sure that it accepts both int and float

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading