1

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

John Doe
  • 1,570
  • 3
  • 13
  • 22
  • there is not, python is not strictly typed – Sasha Jun 13 '18 at 11:28
  • so what does this syntax means ? a:var->int ? And I know it is not stricly typed but my question is : or, is there a way to give an indication? – John Doe Jun 13 '18 at 11:29
  • and I don't know why someone would feel the urge to downvote the question.. I am just looking for the vocabulary involved to be able to search the PEP for advice. – John Doe Jun 13 '18 at 11:33
  • Check out https://docs.python.org/3/library/typing.html – twolffpiggott Jun 13 '18 at 11:35
  • Possible duplicate of [What does -> mean in Python function definitions?](https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions) – bipll Jun 13 '18 at 11:35
  • @bipII from PEP.484 -> [PEP 3107 introduced syntax for function annotations, but the semantics were deliberately left undefined. There has now been enough 3rd party usage for static type analysis that the community would benefit from a standard vocabulary and baseline tools within the standard library. This PEP introduces a provisional module to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.] [...] so : no it is not. – John Doe Jun 14 '18 at 09:44

1 Answers1

3

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.

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50