You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The following code is valid and idiomatic Python 2 code, but does not typecheck under mypy --py2:
from __future__ importunicode_literalsimportosos.environ['key'] ='value'
It yields the error:
os_environ.py:4: error: Invalid index type "unicode" for "MutableMapping"
os_environ.py:4: error: Incompatible types in assignment (expression has type "unicode", target has type "str")
From a bit of poking at it in the repl, it seems that os.environ is a dict-like object which functions a bit like cStringIO: it accepts either str or unicode objects, but throws a runtime encoding error when passed a unicode object which cannot be encoded to the ascii codec:
In #869, I suggested replacing the type signature with MutableMapping[Union[str, unicode], Union[str, unicode]], to which @JukkaLreplied:
This is potentially problematic, since this may break a lot of existing code using os.environ that assumes that it only has str keys and values (and there are other potential issues as well).
I think the type I suggested there is accurate, since annoyingly, these unicode objects' type information does seem to be retained and actually can break code at runtime that assumes it's only getting str:
That said, if there is interest in something more backwards-compatible with previously annotated code, we could allow assignment of str key/values, but assume the actual contents of the mapping are str. I think the following update to os/__init__.pyi would achieve this effect, and might be a good compromise:
The following code is valid and idiomatic Python 2 code, but does not typecheck under
mypy --py2
:It yields the error:
From a bit of poking at it in the repl, it seems that
os.environ
is a dict-like object which functions a bit likecStringIO
: it accepts eitherstr
orunicode
objects, but throws a runtime encoding error when passed aunicode
object which cannot be encoded to theascii
codec:In #869, I suggested replacing the type signature with
MutableMapping[Union[str, unicode], Union[str, unicode]]
, to which @JukkaL replied:I think the type I suggested there is accurate, since annoyingly, these
unicode
objects' type information does seem to be retained and actually can break code at runtime that assumes it's only gettingstr
:That said, if there is interest in something more backwards-compatible with previously annotated code, we could allow assignment of
str
key/values, but assume the actual contents of the mapping arestr
. I think the following update toos/__init__.pyi
would achieve this effect, and might be a good compromise:Please advise, and I'd be happy to submit a pull request once a decision has been reached.
The text was updated successfully, but these errors were encountered: