Explicitly Define Datatype in Python Function

Tags: , , , ,



I want to define 2 variables in python function and define them as float explicitly. However, when i tried to define them in the function parameter, it’s showing syntax error.

Please help me get the desired output.

Here is the code:

def add(float (x) , float (y)) :
    z = (x+y)
    return (print ("The required Sum is: ", z))

add (5, 8)

Answer

Python is a strongly-typed dynamic language, which associates types with values, not names. If you want to force callers to provide data of specific types the only way you can do so is by adding explicit checks inside your function.

Fairly recently type annotations were added to the language. and now you can write syntactically correct function specifications including the types of arguments and return values. The annotated version for your example would be

def add(x: float, y: float) -> float:
    return x+y

Note, though, that this is syntax only. Nothing in the Python interpreter actions any of this. There are external tools like mypy that can help you to achieve your goal, though they are still in their infancy.



Source: stackoverflow