Reputation: 1639
Is there a way to enforce the type of a variable in a python function ? Or at least, give an indication of what it should be ? I already saw things like :
var -> int
But I don't know the name of that syntax, nor its use.
Thanks
Upvotes: 1
Views: 114
Reputation: 10782
It's called Type Hints
, has been introduced in Python 3.5 and is described here: https://docs.python.org/3/library/typing.html
See also PEP 484: https://www.python.org/dev/peps/pep-0484/
Example:
def greeting(name: str) -> str:
return 'Hello ' + name
Note that this will not enforce the type.
From the PEP:
While these annotations are available at runtime through the usual
__annotations__
attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily.
Upvotes: 3