Type inference
Python is a dynamically typed language, which means the types are only known at runtime. However, we can use type inference to declare the type that something is intended to be.
def sum(left: int, right: int):
return left + right
sum(10,0)
This works for classes, variables, functions and anything that has a type.
class File:
size: float
path: str
def __int__(self,size: float, path: str):
self.path = path
self.size = size
file: File = File(20204.2,"./img.png")
Please note, however, that these are merely hints and python is determining the types at runtime. Which means that it will not throw errors simply because the wrong type was supplied.
def output(message: str):
print(message)
# Will not raise an error
output(10)
Type inference is still important, most IDEs will raise warnings whenever a wrong type is used. It also helps callers know what types everything is, and there are tools that check the codebase for invalid types before running.
Return types
The return type of a function may be specified using an arrow, ->
, and the type after.
def multiply(left: float, right: float) -> float:
return left * right