Skip to content

Using class-typed variable as first argument to map #3092

Closed
@pkch

Description

@pkch

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions