Assigning an introspectable comment to variable names

I will be moving the admin of certain setup variables from a third party tool to a new stand-alone tool that will provide the original functionality but add to that the commenting on variables defined.

I spent the weekend looking and it seems that there are several conventions for documentation tools such as:

  • Use the comment on the line before the variable is assigned.
  • Use the string literal following the variable assignment.

I found the use of typing.Annotations, and it seems an OK, but wordy solution.

I can do the following:

from typing import Annotated

class MyClass():

# To comment variables in an introspection-friendly manner I can use:
my_var1: Annotated[MyClass, "Comment on what my_var1 is used for"]
my_var2: Annotated[MyClass, "Still a MyClass object but comment on what my_var2 is used for"]

assert __annotations__ == {'my_var1': typing.Annotated[__main__.MyClass,
                                                       'Comment on what my_var1 is used for'],
                           'my_var2': typing.Annotated[__main__.MyClass,
                                                       'Still a MyClass object but comment on what my_var2 is used for']}

I would like to remove the need to write MyClass every time, something akin to:

def MyAnn: ...  # ??

my_var3: MyAnn["third comment"]
my_var3: MyAnn["fourth comment"]

# And end up with:
assert __annotations__ == {# ...
                           'my_var3': typing.Annotated[__main__.MyClass,
                                                       'third comment'],
                           'my_var4': typing.Annotated[__main__.MyClass,
                                                       'fourth comment']}

Is it possible to give MyAnn the required functionality?

Thanks in advance.

1 Like

Not sure exactly what you’re trying to do, but if you want to:

  • Just attach string annotations to variables so that they can be recovered at runtime,
  • don’t care about having static type checking work or if the annotations are correct,
  • and want to save the quite small number of extra characters from your OP,

you could just do:

# contents of 

global_var: "comment"
# when introspecting:

Your example already contains all the ingredients for this so I’m not sure if there’s some reason you don’t want this.
(Note though that type checkers such as mypy will flag this as using an invalid type hint.)

1 Like

Hi, The Annotations method would be mypy agnostic according to the docs. I don’t think I have to use type checking, but wanted to find the boundaries.

When messing around I think it would not allow me to sub class Annotated so thought I’d ask😊

1 Like