pycharm type checker expected type dict, got 'None' instead

James Caccese picture James Caccese · Jul 20, 2017 · Viewed 10k times · Source

In this snippet:

from typing import Dict, Optional 
class T:
    def __init__(self):
        self.bla = {}

    def t(self) -> Dict:
        if self.bla is None:
            self.bla = {'not none': 'nope!'}
        return self.bla

Can anyone explain why intellij / pycharm's type checker thinks the return value of this method is None?

code snippet with error message

The type checker only seems satisfied if I annotate the return type of t() to be Optional[Dict], but this method can never return None, so I don't think it should be optional.

If I change the initial value of self.bla in __init__() to {} it still things the return value is None. Same error if I use a str instead of a dict

Answer

tshalif picture tshalif · Oct 25, 2019

With the following -> Dict or None annotation pycharm (2019.2) does not complain and I get dict type autocompletion for fdictnoneres:

def fdictnone() -> Dict or None:
    return dict(a=1, b=2)


fdictnoneres = fdictnone()

When using TypeVar pycharm does not provide dict type autocompletion for tfunres:

from typing import TypeVar


T = TypeVar('T', dict, None)


def tfun() -> T:
    return dict(a=1, b=2)


tfunres = tfun()