Open fizbin opened 7 months ago
I don't know the exact underlying problem, but in the stub we mimic the implementation by overriding items()
and inheriting values()
from MutableMapping
. Potentially, we should derive from MutableMapping[str, SectionProxy]
, instead of MutableMapping[str, _Section]
, but I'm not sure whether that's the right solution or not.
Potentially, we should derive from
MutableMapping[str, SectionProxy]
, instead ofMutableMapping[str, _Section]
, but I'm not sure whether that's the right solution or not.
It isn't. The issue is that for purposes of setting values, any Mapping[str, str]
will work, but when you get a value, what you get back is always a SectionProxy
.
See the implementation of these two methods on RawConfigParser
, from which ConfigParser
descends:
def __getitem__(self, key):
if key != self.default_section and not self.has_section(key):
raise KeyError(key)
return self._proxies[key]
def __setitem__(self, key, value):
# To conform with the mapping protocol, overwrites existing values in
# the section.
if key in self and self[key] is value:
return
# XXX this is not atomic if read_dict fails at any point. Then again,
# no update method in configparser is atomic in this implementation.
if key == self.default_section:
self._defaults.clear()
elif key in self._sections:
self._sections[key].clear()
self.read_dict({key: value})
I suspect that the solution is to, in the stub, override items
, values
and __getitem__
to return types based on SectionProxy
.
Consider these two similar python programs, which have identical behavior:
and
(The only difference between the two programs is invoking
cparser.items()
orcparser.values()
)The first program type-checks in
mypy
without any issues, but the second program:The problem is that
ConfigParser
objects accept assignment of arbitrarystr
->str
mappings but when you pull a value back out of aConfigParser
, the value pulled out is always aconfigparser.SectionProxy
. (see the__getitem__
and__setitem__
methods onconfigparser.RawConfigParser
)Note that this affects not only the return type of
values
but also the return type of__getitem__
; it should be perfectly well-typed to writecparser[some_str_value].name
.