Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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()
–
–
This way, the variables are recognised separately. Note however, that this solution is stupid -- you're just doing a workaround for what I would consider a bug in PyCharm! In fact, I have the same problem and still no solution...
For now I would suggest either ignoring the warning or forcing PyCharm to ignore it by adding:
# noinspection PyTypeChecker
I have read somewhere, that the type hinting is not fully implemented yet in PyCharm, so that might still come... I don't remember where I read this though, so no guarantee!
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
–
I'm pretty sure it's because it is initialized as None on your constructor.
I believe if you explicitly state the type in the class definition it should work. Eg:
class T:
bla: Dict
def __init__(self):
self.bla = None
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.