Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python mypy“;“无效类型”;错误_Python_Mypy - Fatal编程技术网

Python mypy“;“无效类型”;错误

Python mypy“;“无效类型”;错误,python,mypy,Python,Mypy,我试图在当前项目中实现类型注释,但从mypy收到了我不理解的错误 我正在使用Python2.7.11,并且在我的基础virtualenv中新安装了mypy。以下程序运行正常: from __future__ import print_function from types import StringTypes from typing import List, Union, Callable def f(value): # type: (StringTypes) -> String

我试图在当前项目中实现类型注释,但从mypy收到了我不理解的错误

我正在使用Python2.7.11,并且在我的基础virtualenv中新安装了mypy。以下程序运行正常:

from __future__ import print_function
from types import StringTypes
from 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')))
但是运行
mypy--py2-s mypy_issue.py
会返回以下结果:

mypy_issue.py: note: In function "f":
mypy_issue.py:8: error: Invalid type "types.StringTypes"

上述类型似乎在。。。mypy说“mypy合并了typeshed项目,其中包含Python内置库和标准库的库存根。”。。。不确定“合并”是什么意思-我是否需要做一些事情来“激活”或提供一条到Typeshed的路径?我是否需要在本地下载并安装(?)Typeshed?

问题在于
类型。StringTypes
被定义为一系列类型——正式的类型签名是:

这对应于,表示
StringTypes
常量是“包含
StringType
UnicodeType
的序列”

因此,这就解释了您所遇到的错误--
StringTypes
不是一个实际的类(它可能是一个元组),因此mypy无法将其识别为有效类型

有几种可能的修复方法

第一种方法可能是使用
typing.AnyStr
,定义为
AnyStr=TypeVar('AnyStr',bytes,unicode)
。尽管
AnyStr
包含在
typing
模块中,但不幸的是,到目前为止,它的文档记录还不完善——您可以找到关于它的功能的更详细信息

一种稍微不那么简洁的表达方式是:

from types import StringType, UnicodeType
from typing import Union

MyStringTypes = Union[StringType, UnicodeType]

def f(value):     
    # type: (MyStringTypes) -> MyStringTypes
    return value
这也是可行的,但不太理想,因为返回类型不再必须与输入类型相同,而输入类型在处理不同类型的字符串时通常不是您想要的


至于typeshed——在安装mypy时,默认情况下它是捆绑的。在理想情况下,您根本不需要担心typeshed,但由于mypy处于测试阶段,因此typeshed经常被更新,以解释丢失的模块或不正确的类型注释,如果您发现自己经常在typeshed中遇到错误,那么直接从安装程序安装mypy并在本地安装typeshed可能是值得的。

感谢您的详细解释!非常感谢。@SolomonUcko--No。问题是
类型
标准库模块早于类型提示,更适合于运行时使用,而不是类型提示。尽管名称不同,mypy(以及任何其他兼容PEP 484的类型检查器)都不会将
StringTypes
识别为有效类型:它最终被视为仅包含两种类型的元组。我的建议是避免在类型提示的上下文中使用
类型
模块中的任何内容。相反,尽可能使用
typing
模块中的内容——因此在本例中,可以使用
typing.AnyStr
Union[str,typing.Text]
from types import StringType, UnicodeType
from typing import Union

MyStringTypes = Union[StringType, UnicodeType]

def f(value):     
    # type: (MyStringTypes) -> MyStringTypes
    return value