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?

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
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()
I found Type hinting the instance variable works. I also don't seem to incur the original inspection error in the 2018 pro version of pycharm, so I'm wondering if they've updated the inspection to be a little smarter.
class T(object):
def __init__(self):
self.bla:Dict = None
def t(self) -> Dict:
if self.bla is None:
self.bla = {'foo' : 'bar'}
return self.bla
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With