Closed
Description
How do I annotate a function that takes a class argument and uses it as the first argument in map
?
A structural type would fit perfectly, but those aren't part of mypy
yet.
Using Type[X]
doesn't work:
class X:
def __init__(self, x: int) -> None:
pass
def f(cls: Type[X]) -> None:
map(cls, [1, 2, 3]) # No overload variant of "map" matches argument types [Type[b.X], builtins.list[builtins.int*]]
Not sure if it's intentional or not, but it's somewhat understandable since Type[X]
may be a subclass of X
rather than X
itself, and so there's no guarantee its __init__
accepts an int
argument.
I tried to fall back to just type
, but it still failed because even though cls
can be called with an integer argument and returns Any
, type
isn't accepted as a subtype of Callable[[T], S]
:
def g(cls: type) -> None:
reveal_type(cls(1)) # Any
map(cls, [1, 2, 3]) # No overload variant of "map" matches argument types [builtins.type, builtins.list[builtins.int*]]
Edit: after I fixed a typo, using Callable
ended up working:
def h(cls: Callable[[int], S]) -> None:
map(cls, [1, 2, 3])
h(X)
Is this the right way to deal with it?
Metadata
Metadata
Assignees
Labels
No labels