Skip to content

classmethod and selftype: incompatible with supertype #2511

@thomascellerier

Description

@thomascellerier

I am defining some classes capable of returning an (optional) instance of themselves based on a configuration (a dictionary).

In the base class I use the new SelfType capability to define the generic classmethod. I wanted to use a metaclass with abc.abstractclassmethod but mypy doesn't seem to support that.

In the subclass I now use the narrower type for cls and the return value but mypy gives me an error:

$ ./virtualenv/bin/python3 -m mypy --version
mypy 0.4.6
$ ./virtualenv/bin/python3 -m mypy repro.py 
repro.py: note: In class "B":
repro.py:15: error: Return type of "from_config" incompatible with supertype "A"

repro.py:

from typing import TypeVar, Type, Optional

AT = TypeVar('AT', bound='A')

class A:
    @classmethod 
    def from_config(cls: Type[AT], config: dict) -> Optional[AT]:
        return None

class B(A):
    @classmethod
    def from_config(cls: Type[B], config: dict) -> Optional[B]:
        return B()

I could only make it work by defining B like this which looks quite ugly and requires passing around the type variable:

from typing import cast

class B(A):
    @classmethod
    def from_config(cls: Type[AT], config: dict) -> Optional[AT]:
        return cast(AT, B())

Is that the intended result?

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    pFad - Phonifier reborn

    Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

    Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


    Alternative Proxies:

    Alternative Proxy

    pFad Proxy

    pFad v3 Proxy

    pFad v4 Proxy