Skip to content

How to type-hint collections.UserList subclasses? #718

Closed

Description

What is a proper way to type hint collections.UserList subclasses? This doesn't work for me:

class SerializableItem:
    def __init__(self, model: Type[ConfigModel], config: SerializationConfig) -> None:
        self.model = model
        self.config = config

class SerializableItems(UserList[SerializableItem]):
    def __init__(self) -> None:
        pass

    def getConfigModelForExtension(self, fileExtension: str) -> Type[ConfigModel]:
        for serItem in self:
            if serItem.config.fileExt == fileExtension:
                return serItem.model

Runtime error: TypeError: 'ABCMeta' object is not subscriptable userList

How do I correctly type-hint SerializableItems - list of objects of what types?
This works for me, but line self.data: List[SerializableItem] does not seem the right thing to do.

class SerializableItems(UserList):
    def __init__(self) -> None:
        super().__init__()
        self.data: List[SerializableItem]

    def getConfigModelForExtension(self, fileExtension: str) -> Type[ConfigModel]:
        for serItem in self.data:
            if serItem.config.fileExt == fileExtension:
                return serItem.model

        raise Exception(f"Can't find ConfigModel for file extension '{fileExtension}'")

Without type hint IDE can't help me with autocomplete on a line if serItem.config. in getConfigModelForExtension().

Python 3.6 64-bit, VS Code + latest Pylance extension

Activity

  1. erictraut commented on Dec 11, 2020

    @erictraut
    Contributor

    This is due to a limitation of Python 3.6. The UserList is declared in the typeshed stubs as a generic class, so it is expected to have a type argument. But at runtime, Python 3.6 didn't support this. It was fixed in Python 3.7.

    Your workaround will avoid the runtime error, but it has the side effect of not providing full autocomplete because the type checker has effectively been told that the class inherits from UserList[Any].

    I don't see a good solution here other than to upgrade to Python 3.7.

  2. grddavies commented on Mar 15, 2022

    @grddavies

    I'm still having this issue with python 3.8.10

  3. debonte commented on Mar 15, 2022

    @debonte
    Contributor

    Gethin Davies (@grddavies), since this issue is closed, please create a new issue describing what you are seeing. Linking your new issue to this one would be helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions