Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly Define Datatype in Python Function

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)
like image 769
Animikh Aich Avatar asked Apr 05 '17 14:04

Animikh Aich


3 Answers

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, which are now maturing fast to become an established part of the language (though one hopes they will remain strictly optional, bearing in mind the vast corpus of type-free code that exists).

Annotations are finding a wider use than originally intended in tools like pydantic, which uses them to perform data validation. This supports interesting new paradigms, exploited by (for example) the FastAPI server, demonstrating great potential to improve web coding productivity.

like image 141
holdenweb Avatar answered Oct 08 '22 16:10

holdenweb


you can check however the instance that is provided in the function if its the type you want!

def add(x: float, y: float) -> float:
      if not isinstance(x, float):
           raise TypeError("x and y variables not of type float")

similarly for the y var!

like image 3
chg.greg Avatar answered Oct 08 '22 16:10

chg.greg


It is not possible to define Data-Type in Python as it is strongly typed dynamic language , but it is possible to add Type-Hint .

link: str

This is a sample of type-hint in python. You can also check-out.

Also take a look at mypy:

  • https://github.com/python/mypy
  • http://mypy-lang.org/
like image 1
Maifee Ul Asad Avatar answered Oct 08 '22 17:10

Maifee Ul Asad