Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 642
James Caccese Avatar asked Jul 20 '17 15:07

James Caccese


2 Answers

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()
like image 120
tshalif Avatar answered Oct 19 '22 05:10

tshalif


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
like image 37
Marcel Wilson Avatar answered Oct 19 '22 04:10

Marcel Wilson