i'm trying implement type annotations in current project, , receiving errors mypy don't understand.
i'm using python 2.7.11, , newly installed mypy in base virtualenv. following program runs fine:
from __future__ import print_function types import stringtypes typing import list, union, callable def f(value): # type: (stringtypes) -> stringtypes return value if __name__ == '__main__': print("{}".format(f('some text'))) print("{}".format(f(u'some unicode text')))
but running mypy --py2 -s mypy_issue.py
returns following:
mypy_issue.py: note: in function "f": mypy_issue.py:8: error: invalid type "types.stringtypes"
the above types appear in typeshed... mypy documentation says "mypy incorporates typeshed project, contains library stubs python builtins , standard library. "... not sure "incorporates" means - need "activate", or provide path to, typeshed? need download , install(?) typeshed locally?
the problem types.stringtypes
defined sequence of types -- formal type signature on typeshed is:
stringtypes = (stringtype, unicodetype)
this corresponds official documentation, states stringtypes
constant "a sequence containing stringtype
, unicodetype
"...
so then, explains error you're getting -- stringtypes
isn't actual class (it's tuple) , mypy doesn't recognize valid type.
there several possible fixes this.
the first way use typing.anystr
defined anystr = typevar('anystr', bytes, unicode)
. although anystr
included within typing
module, is, unfortunately, poorly documented of -- can find more detailed information within mypy docs.
a less cleaner way of expression do:
from types import stringtype, unicodetype typing import union mystringtypes = union[stringtype, unicodetype] def f(value): # type: (mystringtypes) -> mystringtypes return value
this works, less desirable because return type no longer obligated same thing input type not want when working different kinds of strings.
and typeshed -- it's bundled default when install mypy. in ideal world, shouldn't need worry typeshed @ all, since mypy in beta , typeshed being updated account missing modules or incorrect type annotations, might worth installing mypy directly github repo , installing typeshed locally if find running bugs typeshed.
Comments
Post a Comment