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.
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!
Starting with Python 3.6, you can declare types of variables and functions, like this :
explicit_number: type
or for a function
def function(explicit_number: type) -> type:
pass
This example from this post: How to Use Static Type Checking in Python 3.6 is more explicit
from typing import Dict
def get_first_name(full_name: str) -> str:
return full_name.split(" ")[0]
fallback_name: Dict[str, str] = {
"first_name": "UserFirstName",
"last_name": "UserLastName"
}
raw_name: str = input("Please enter your name: ")
first_name: str = get_first_name(raw_name)
# If the user didn't type anything in, use the fallback name
if not first_name:
first_name = get_first_name(fallback_name)
print(f"Hi, {first_name}!")
See the docs for the typing module
Edit: Python 3.5 introduced type hints which introduced a way to specify the type of a variable. This answer was written before this feature became available.
There is no way to declare variables in Python, since neither "declaration" nor "variables" in the C sense exist. This will bind the three names to the same object:
x = y = z = 0