Skip to content

Help genericising a class #3824

@OddBloke

Description

@OddBloke

I have the following class:

class DictWrapper:

    def __init__(self, dict_type: Type[MutableMapping]) -> None: ...

    def get_internal_thing(self) -> MutableMapping[str, str]: ...

which seems to work fine. However, if I want to be able to treat the return value of get_internal_thing as the type that was passed in to __init__ (e.g. DictWrapper(OrderedDict).get_internal_thing().move_to_end('a')) then I (unsurprisingly) run in to problems.

I've tried genericising it like this:

T = TypeVar('T')


class GenericDictWrapper(Generic[T]):

    def __init__(self, dict_type: Type[T]) -> None: ...

    def get_internal_thing(self) -> T: ...

As I've dropped all reference to str, it's not especially surprising that it doesn't work;

GenericDictWrapper(OrderedDict).get_internal_thing().move_to_end('a')

gives:

test.pyi:22: error: Argument 1 to "move_to_end" of "OrderedDict" has incompatible type "str"; expected "_KT"

I'm not really sure where to proceed from here; it really feels like I'm missing something. Can anyone help me out?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions