Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting or annotating a function

Tags:

python

According to the PEP 526 -- Syntax for Variable Annotations you can do comments to annotate a function like this:

def comment():
    num: int = 5
    print ('COMMENTS', __annotations__)

Why doesn't this work then?

>>> comment()
COMMENTS {}

2 Answers

If you read the PEP you linked, you will find the following text:

Annotating a local variable will cause the interpreter to treat it as a local, even if it was never assigned to. Annotations for local variables will not be evaluated:

def f():
    x: NonexistentName  # No error.

However, if it is at a module or class level, then the type will be evaluated:

x: NonexistentName  # Error!
class X:
    var: NonexistentName  # Error!

In addition, at the module or class level, if the item being annotated is a simple name, then it and the annotation will be stored in the __annotations__ attribute of that module or class (mangled if private) as an ordered mapping from names to evaluated annotations. Here is an example:

from typing import Dict
class Player:
    ...
players: Dict[str, Player]
__points: int

print(__annotations__)
# prints: {'players': typing.Dict[str, __main__.Player],
#          '_Player__points': <class 'int'>}

Local variable annotations are not evaluated and are not stored in an __annotations__ dict. There are no __annotations__ dicts for local variables at all, in fact; you're printing the __annotations__ for the module globals.

like image 153
user2357112 supports Monica Avatar answered Sep 13 '26 09:09

user2357112 supports Monica


You should read the full text of PEP 526 (emphasis mine):

Note that if annotations are not found statically, then the __annotations__ dictionary is not created at all. Also the value of having annotations available locally does not offset the cost of having to create and populate the annotations dictionary on every function call. Therefore annotations at function level are not evaluated and not stored.

like image 27
Selcuk Avatar answered Sep 13 '26 09:09

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!