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

6
  • there is not, python is not strictly typed Commented Jun 13, 2018 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? Commented Jun 13, 2018 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. Commented Jun 13, 2018 at 11:33
  • Check out docs.python.org/3/library/typing.html Commented Jun 13, 2018 at 11:35
  • Possible duplicate of What does -> mean in Python function definitions? Commented Jun 13, 2018 at 11:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

To enforce the type, just add ad an assertion in your function assert type(name) is str

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.