Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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
Mypy Python 2坚持unicode值而不是字符串值_Python_Python 2.7_Mypy - Fatal编程技术网

Mypy Python 2坚持unicode值而不是字符串值

Mypy Python 2坚持unicode值而不是字符串值,python,python-2.7,mypy,Python,Python 2.7,Mypy,在某些情况下,Python 2会隐式地将str转换为unicode。此转换有时会抛出一个UnicodeError,具体取决于您对结果值的处理方式。我不知道确切的语义,但这是我想避免的 除了unicode或类似于--strict optional()的命令行参数之外,是否可以使用其他类型导致使用此隐式转换的程序无法进行类型检查 def returns_string_not_unicode(): # type: () -> str return u"a" def return

在某些情况下,Python 2会隐式地将
str
转换为
unicode
。此转换有时会抛出一个
UnicodeError
,具体取决于您对结果值的处理方式。我不知道确切的语义,但这是我想避免的

除了
unicode
或类似于
--strict optional
()的命令行参数之外,是否可以使用其他类型导致使用此隐式转换的程序无法进行类型检查

def returns_string_not_unicode():
    # type: () -> str
    return u"a"

def returns_unicode_not_string():
    # type: () -> unicode
    return "a"
在本例中,只有函数
返回\u string\u not \u unicode
无法进行类型检查

$ mypy --py2 unicode.py
unicode.py: note: In function "returns_string_not_unicode":
unicode.py:3: error: Incompatible return value type (got "unicode", expected "str")
我希望他们两个都不能通过打字检查

编辑:

type:()->byte
的处理方式似乎与
str

def returns_string_not_unicode():
    # type: () -> bytes
    return u"a"

不幸的是,这是一个正在进行且目前尚未解决的问题——请参阅和

一个部分修复方法是使用
键入.Text
,不幸的是,它目前没有文档记录(不过我会努力修复)。它在Python3中别名为
str
,在Python2中别名为
unicode
。它不会解决您的实际问题,也不会导致第二个函数无法进行类型检查,但它确实使编写与Python2和Python3兼容的类型变得更加容易

同时,您可以通过使用最近实现的来拼凑一个部分解决方案——它允许您以最小的运行时成本定义一个psuedo子类,您可以使用它来近似您所寻找的功能:

from typing import NewType, Text

# Tell mypy to treat 'Unicode' as a subtype of `Text`, which is
# aliased to 'unicode' in Python 2 and 'str' (aka unicode) in Python 3
Unicode = NewType('Unicode', Text)

def unicode_not_str(a: Unicode) -> Unicode:
    return a

# my_unicode is still the original string at runtime, but Mypy
# treats it as having a distinct type from `str` and `unicode`.
my_unicode = Unicode(u"some string")

unicode_not_str(my_unicode)      # typechecks
unicode_not_str("foo")           # fails
unicode_not_str(u"foo")          # fails, unfortunately
unicode_not_str(Unicode("bar"))  # works, unfortunately
它并不完美,但如果您在将字符串提升为自定义
Unicode
类型时有原则,则在字节/str/Unicode问题解决之前,您可以获得近似您所寻找的类型安全性的东西,而运行时成本最低

注意,要使用
NewType
,您需要从Github的主分支安装mypy


请注意,NewType是从添加的。

请查看将返回类型声明为
字节是否有帮助。@user2357112似乎没有。