You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
OrderedDict() needs type annotation but {} doesn't #4551
The following error message is triggered when by adding -> Dict[Text, Any] to the type signature:
/tmp/pod.py:7: error: Need type annotation for 'result'
This is the contents of /tmp/pod.py:
import collections
from typing import Any, Dict, Text
class PlainOldData:
def as_json_dict(self) -> Dict[Text, Any]:
result = collections.OrderedDict()
for k in self.__slots__:
value = getattr(self, k)
if value is not None:
result[k] = value
return result
Oops ... the problem I was trying to report (about slots) turned out to be due to having __slots__ = () (which gets overridden in subclasses) and I needed to annotate that even though object.slots has an appropriate definition in typeshed.
As for OrderedDict ... shouldn't it work? When I change the code to result = {}, mypy is happy.
The issue with __slots__ is #4547 then, while the issue with result is interesting... if I had to guess mypy is inferring the type of {} based on the return type but fails to do so in your real code since it is an OrderedDict.
Mypy has custom type inference rules for common collection types such as List and Dict, but they don't apply to OrderedDict. It would be nice if we could generalize this to (almost) arbitrary collection types.
Activity
emmatyping commentedon Feb 8, 2018
Since mypy doesn't know the type of the ordered dict when you create it, you need to add a type annotation.
kamahen commentedon Feb 8, 2018
Oops ... the problem I was trying to report (about slots) turned out to be due to having
__slots__ = ()(which gets overridden in subclasses) and I needed to annotate that even though object.slots has an appropriate definition in typeshed.As for OrderedDict ... shouldn't it work? When I change the code to
result = {}, mypy is happy.emmatyping commentedon Feb 8, 2018
The issue with
__slots__is #4547 then, while the issue withresultis interesting... if I had to guess mypy is inferring the type of{}based on the return type but fails to do so in your real code since it is anOrderedDict.[-]Bogus "need type annotation" for __slots__[/-][+]OrderedDict() needs type annotation but {} doesn't[/+]JukkaL commentedon Feb 8, 2018
Mypy has custom type inference rules for common collection types such as
ListandDict, but they don't apply toOrderedDict. It would be nice if we could generalize this to (almost) arbitrary collection types.emmatyping commentedon Dec 27, 2024
The example below (updated to have type information to express subclasses will have
__slots__):passes with the latest mypy, closing.