Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OrderedDict() needs type annotation but {} doesn't #4551

Open
kamahen opened this issue Feb 8, 2018 · 4 comments
Open

OrderedDict() needs type annotation but {} doesn't #4551

kamahen opened this issue Feb 8, 2018 · 4 comments

Comments

@kamahen
Copy link
Contributor

kamahen commented Feb 8, 2018

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
@ethanhs
Copy link
Collaborator

ethanhs commented 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
Copy link
Contributor Author

kamahen commented 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.

@ethanhs
Copy link
Collaborator

ethanhs commented Feb 8, 2018

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.

@kamahen kamahen changed the title Bogus "need type annotation" for __slots__ OrderedDict() needs type annotation but {} doesn't Feb 8, 2018
@JukkaL
Copy link
Collaborator

JukkaL commented Feb 8, 2018

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.

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

No branches or pull requests

3 participants