How to Type Hint part of *args #1779
-
I have a function where I know what the first positional argument type should be, but the remaining ones are undefined. Is there any way to specify only the first argument? The exact function signature is, def f(*args, **kwargs): and the type I want is roughly like def f(args: [int, Any], **kwargs: Any) -> int: So even though most of the types are Any, the return type and first input type are known and those are the most important ones to me (partly as other arguments are rare). It's reasonable to argue that I should refactor an argument out, but I mostly am curious about this type hint for a key function in a large 3rd party library and changing its signature is unlikely. If there's no other way then I'll make a wrapper around it for actual usage. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
If I understand you correctly, the signature would be this: def f(_p0: int, *args: Any, **kwargs: Any) -> int:
... Or are you asking how to specify this as a Although class CallbackWithInt(Protocol):
def __call__(self, _p0: int, *args: Any, **kwargs: Any) -> int:
... |
Beta Was this translation helpful? Give feedback.
If I understand you correctly, the signature would be this:
Or are you asking how to specify this as a
Callable
type annotation?Callable
doesn't allow this combination. (You can specifyCallable[..., int]
, but there's no way to indicate that the first parameter should be anint
.)Although
Callable
is somewhat limiting, you can escape those limits by using a callback protocol. It would look like this: