python – Why call "-> max (a, b)" when creating a function?

Question:

Found this example:

def function(a:int,b:str,c:list) -> max(2,3):

Why is -> max(...) ?

Answer:

In this line

def function(a:int,b:str,c:list) -> max(2,3):

:int :str :list , -> max(2,3) are annotations. They were first proposed for introduction in Python in PEP 3107 , but their purpose was not clearly defined (their interpretation was left to the authors of third-party tools).

Any syntactically valid Python expression can be used as annotation. When the interpreter runs the code, the expressions used as annotations are executed (therefore, they can cause errors at runtime, for example, the expression def f() -> max(None, 1): pass will raise a TypeError , an example from jfs ), but in no special way are not processed by the interpreter (i.e., for example, the interpreter itself does not check types).

Later, the use of annotations as type annotations was more clearly documented ( PEP 484 ), i.e. after the function arguments, separated by a colon, we write the expected type of the argument, after -> we write the type of the return value of the function.

Again, the interpreter ignores them, but type annotations can be used by tools such as mypy or PyCharm's built-in static code analyzer to understand that a function was passed (or returned) a value of the wrong type, and display this as an error or warning. …

-> max(2,3) from my point of view does not carry any semantic load. It is not a type annotation, but just an annotation. What the author of the example meant is a mystery. Most likely this is just an example of using annotations.

You can programmatically access function annotations through the function's __annotations__ attribute:

def function(a:int,b:str,c:list) -> max(2,3): pass

print(function.__annotations__)

Result:

{'a': <class 'int'>, 'return': 3, 'c': <class 'list'>, 'b': <class 'str'>}

Here you can see the types prescribed for the arguments, and you can see that the expression max(2,3) calculated, so just 3 was written as an annotation for the return value.

Scroll to Top