Add docstrings to variables in TypedDicts?

Just reading through SO posts, it seems this isn’t possible:

class MyClass(TypedDict):

  """runtime config"""
  r_config: bool

And get a docstring, for each variable defined within. Is there plans to add this or workarounds people use?

I’m aware one could document all together in a class, but user gets no typehints when hovering over a key in the code.

That code runs for me (3.13.1), and checks out with mypy (1.13.0 (compiled: yes)) (after importing TypedDict). This too:

from typing import TypedDict

class MyClass(TypedDict):

  """runtime config"""
  r_config: bool
  
  """runtime config 2"""
  r_config_2: bool

MyClass.__doc__ is the first one (runtime_config). The r_config(_2)? are names for dictionary keys not class variables, so I’m not sure where to look for doc strings, and wouldn’t expect them to have them.

2 Likes

so I’m not sure where to look for doc strings,

That’s the question. Indeed I used the wrong term, it’s just how to document dictionary keys the question.

It can not be added currently, I’m not sure whether there is some workaround.

In Python, the convention is to put the doc string below the thing that it documents, instead of above.

When I put the above code in VSCode and put my mouse over r_config, a mouseover tooltip appears with the docstring “runtime config 2”. So “runtime config 2” is associated with r_config.

If I use this code:

class MyClass(TypedDict):
    """ class docstring here """

    r_config: bool
    """ runtime config """

    r_config_2: bool
    """ runtime config 2 """

I can put my mouse over r_config and see “runtime config” in the tooltip.
I can put my mouse over r_config_2 and see “runtime config 2” in the tooltip.
I can put my mouse over MyClass and see “class docstring here” in the tooltip.

2 Likes

I just realised though, that it only works within the TypedDict, when a dictionary is assigned the type: my_d: My_Td = {...}

The keys are not typed. Is this correct? So it’s not a solution.