Python Dynamic Type Hints (like Dataclasses)

Viewed 34

I have a dataclass, and a function which will create an instance of that dataclass using all the kwargs passed to it. If I try to create an instance of that dataclass, I can see the type hints/autocomplete for the __init__ method. I just need the similar type hints for a custom function that I want to create.

from dataclasses import dataclass


@dataclass
class Model:
    attr1: str
    attr2: int


def my_func(**kwargs):
    model = Model(**kwargs)

    ...  # Do something else
    ret = [model]

    return ret

# my_func should show that it needs 'attr1' & 'attr2'
my_func(attr1='hello', attr2=65535)
1 Answers

If your IDE isn't sophisticated enough to infer that kwargs isn't used for anything else than to create a Model instance (I'm not sure if there is such an IDE), then it has no way of knowing that attr1 and attr2 are the required arguments, and the obvious solution would be to list them explicitly.

I would refactor the function so that it takes a Model instance as argument instead.

Then you would call it like my_func(Model(...)) and the IDE could offer the autocompletion for Model.

Related