Should mypy raise errors on missing kwargs for __init__ on factory functions? #1191
Replies: 2 comments 5 replies
-
You can use Here's how that would be specified in your example use case. P = ParamSpec("P")
T = TypeVar("T", bound=A)
def foo(cls: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
return cls(*args, **kwargs) |
Beta Was this translation helpful? Give feedback.
-
If I try to use this same approach on a To avoid repetitions, the only change is in the definition of A: class A:
def __init__(self, b: int):
...
@classmethod
def build(cls: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
return cls(*args, **kwargs) I tried changing the function definition here and there but ended up in my original situation (so no error from mypy when args where missing) or with the error I just showed. The semantics of this |
Beta Was this translation helpful? Give feedback.
-
I have been trying to create a factory function for my classes and subclasses.
Most subclasses have common
args
andkwargs
. However, my main problem is that some subclasses havekwargs
that are unique for them.An MRE of my situation is the following:
I'm wondering if a type checker (specifically looking at mypy) should raise errors for both
foo(B)
andfoo(C)
since I'm not passing the requiredkwargs
. Is this something that mypy (or another type-checker) is able to do?My reasoning is that I want to be able to call that function and them mypy tell me if I'm missing any
arg
orkwarg
. I know that I can get the errors by running the interpreter, however, when dealing with several kwargs, it can be time-consuming to execute the run the interpreter several times just to know that I missed a kwarg.NOTE: This is my first discussion/question in this repo so I don't know if this is the best place to ask this question or even if it should be asked here. I very much welcome suggestions/corrections about this topic too 😊. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions