0

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)
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • If you know `my_func` requires `attr1` and `attr2`, put them in the parameter list explicitly. – chepner Sep 20 '22 at 19:55
  • Or, don't take the arguments needed by `Model` as arguments; take a pre-constructed instance of `Model` instead. – chepner Sep 20 '22 at 19:56
  • 1
    As of now, not yet. However it [may be available in the future](https://peps.python.org/pep-0692/). – Axe319 Sep 20 '22 at 19:56
  • This sounds similar to a question on inferring [init params](https://stackoverflow.com/q/73778158/10237506) for a dataclass that I had previously asked. – rv.kvetch Sep 21 '22 at 03:31

1 Answers1

0

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Yeah, the current code is like this, but the problem was that there were a lot of different models from different files, so I was looking for a way to make it like this. @Axe319 mentioned that type hinting kwargs may be available in future – Lost Traveller Sep 21 '22 at 10:02