Home > Software design >  How to assign data type to a parameter and if that data type is not same as i assigned raise an erro
How to assign data type to a parameter and if that data type is not same as i assigned raise an erro

Time:10-19

Alright, so i was coding when i stumbled upon a problem:

def myFunction(string):
    print(string   "test")

Now, when i put a string, it runs perfectly fine. But, when i put in an int:

myFunction(str(1)):

It still works? Now, i know i put a str() function to the "1" value. But, if i wanted to have a function that takes in a parameter with the data type string, and type an integer value to that parameter, it still works. How can i do it?

CodePudding user response:

One option is to use f-strings, which allows myFunction to concatenate a type other than a string, with a string:

def myFunction(o: object):
    print(f'{o}test')

Or, even better yet:

def myFunction(o: object):
    print(o, 'test', sep='')

Then the desired call should work without needing to wrap the value in str() explicitly:

>>> myFunction(1)
1test

If you prefer to be more explicit, I'd suggest changing it like below; what this does is call str(o) internally, only it looks a bit nicer.

def myFunction(o: object):
    print(f'{o!s}test')
  • Related