Mypy: [question] proper type annotation for __dict__

Created on 7 Mar 2019  路  1Comment  路  Source: python/mypy

I'm wondering which is the correct way of annotating __dict__ property. Dict[str, Any] seem quite obvious and is used multiple times in typeshed, but:

from typing import Any, Dict

class Test:
    @property
    def __dict__(self) -> Dict[str, Any]:
        return {}
% mypy test.py 
test.py:5: error: Signature of "__dict__" incompatible with supertype "object"

Most helpful comment

This appears to be a duplicate of https://github.com/python/mypy/issues/5836. For example see this minimal repro:

class Test:
    a = ""  # type: str

class B(Test):
    @property
    def a(self) -> str:
        return ""

As a workaround in your case, you can likely do something like:

from typing import Dict, Any, TYPE_CHECKING

class Test:
    if TYPE_CHECKING:
        __dict__ = {}  # type: Dict[str, Any]
    else:
        @property
        def __dict__(self) -> Dict[str, Any]:
            return {}

and mypy should be happy.

>All comments

This appears to be a duplicate of https://github.com/python/mypy/issues/5836. For example see this minimal repro:

class Test:
    a = ""  # type: str

class B(Test):
    @property
    def a(self) -> str:
        return ""

As a workaround in your case, you can likely do something like:

from typing import Dict, Any, TYPE_CHECKING

class Test:
    if TYPE_CHECKING:
        __dict__ = {}  # type: Dict[str, Any]
    else:
        @property
        def __dict__(self) -> Dict[str, Any]:
            return {}

and mypy should be happy.

Was this page helpful?
0 / 5 - 0 ratings