Skip to content

type redefinition allowed when value coming from dictionary #8123

Closed

Description

@dpinol
def kk(self, dic: Dict[str, str]) -> None:
  a = 2
  a = dic.get("as", "as2")

correctly complains that the type of a has changed:

error: Incompatible types in assignment (expression has type "Optional[str]", variable has type "int") [assignment]

However

def kk(self, dic: Dict) -> None:
       a = 2
       a = dic.get("as", "default")

does not complain that a type could be changed to str due to the default value in the get call.

Additionally, I'm not sure if the code below should complain since the dictionary may potentially return any type

def kk(self, dic: Dict) -> None:
       a = 2
       a = dic.get("as")

thanks!

Activity

  1. msullivan commented on Dec 10, 2019

    @msullivan
    Collaborator

    The last example is certainly correct behavior.

    The main example is a little hairy. The cause here is that the typeshed stub for get is def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ....
    If we changed the definition to the more obvious def get(self, k: _KT, default: _T) -> Union[_VT_co, _T]: ..., then I think this would work. That change did get made, but we had to revert it because it caused issues python/typeshed#2817.

    I think our conclusion was that #6613 would allow doing that. So I am going to close this issue in favor of that one but add a note to it. Thanks!

  2. dpinol commented on Dec 10, 2019

    @dpinol
    Author

    thank you guys, mypy is amazing

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions