please how can I specify the return values of a function and types of arguments it required , like in C we declare a prototype function like this and type it requires :
int *atoi(char *str)
please how can I specify the return values of a function and types of arguments it required , like in C we declare a prototype function like this and type it requires :
int *atoi(char *str)
You can use this for both arguments and variables. But the problem is the this type can be changed at any time when assigning.
a:int = 4
but this also will work without raising error
a:int = "this is string"
and lets get function arguments
def func(arg1:int , arg2:str = "hello"): -> str
#do something
The above function will take an integer as first argument , string as the second one and will output a string.
But there is no contrains like C or java. Such like arguments must be in the specified data type only. The same is for the output data type also.
Unfortunately, in python there's no definitive ways of constraining. I.e. you can write code like this:
def func(a:int, b:str):
print(type(a))
print(type(b))
func("Hello!", 31)
# >>> <class 'str'>
# >>> <class 'int'>
If you want to set constraints on code, I would suggest setting up a try/except
clause which tries to convert to the correct type, and raises an error if it does not work. Like so:
def func(a:int, b:str):
try:
a = int(a)
except ValueError:
raise ValueError(f"Input {a =} not understood as integer. ")
try:
b = str(b)
except ValueError:
raise ValueError(f"Input {b =} not understood as string. ")
# func("Hello!", 31) # raises value errors.
func(31, "Hello!") # passes. With variables cast to right type.