from typing import *
def my_func(arg1: int, arg2: str, *args, **kwargs) -> MyClass:
a = MyClass(*args, **kwargs)
... # Some code uses arg1 and arg2
return a
my_func passes *args and **kwargs to the MyClass constructor. How to copy constructor’s arguments type annotations to the function for type checking (mypy)?
I don’t believe there’s any way to do this automatically. If you want mypy to be able to check the types, you’d need to define them. mypy is a static tool it cannot and will not inspect your code to figure out where/how your variables may be used within the code at runtime. It only checks whether the types match where they’re defined (or, in simple cases, inferred).
Realistically, it looks like the example you’ve given would be better off just expecting a MyClass instance and the caller to pass one in. Especially because (at least in the example) there’s no preprocessing of the *args or **kwargs before instantiation.
EDIT:
Also, I would avoid using a from <whatever> import * pattern. It makes it unclear which names are in scope. And if you’ve got multiple, it can create unintended name collisions. And it’ll make it harder to read the code. In your example you don’t even seem to be using anything from the typing package. In any case, either import the package and use its members (a little more verbose and not too popular for typing) or import what you need from it explicitly (i.e from typing import Any).
This is simplified case, the real function adds some arguments to the constructor. Also what if MyClass is immutable and the given MyClass instance cannot be modified when constructed without required arguments?
I assume my_func is intended for some class you cannot modify? it really sounds like it should be a class method defined by the class, rather than a standalone function. Can you give a more concrete example of what my_func will do with arg1 and arg2 before calling MyClass to create the return value?
Sorry, Concatenate-ing a TypeVarTuple and a ParamSpec is apparently an unspecified behaviour and thus not supported. I guess the only way is to create multiple definitions.