难以理解带有 --py2 标志的 mypy 中 str() 的行为

trouble understanding the behavior of str() in mypy with --py2 flag

我有一段代码

1. b = u'\xe6' #type: unicode
2. c = str(b) #type: str
3. d = c #type: str

我 运行 这与 mypy 中的 python 2 标志。

我的预期是第 2 行应该有错误。str(b) returns 是一个类型 unicode 并且 c 的预期类型是 str 因此应该存在类型不兼容问题。但是没有抛出任何错误。

另一方面,如果我明确地做

1. b = u'\xe6' #type: unicode
2. c = str(b) #type: unicode
3. d = c #type: str

然后第3行报错,说cannot assign unicode to str,有点意料之中。

那么问题出在我对str()的理解上,str()return不应该与其输入的类型相同吗?或者它是否隐式地将所有内容都转换为 str,如果是,那么第二个示例中的第 2 行而不是第 3 行不应该有错误。

从目前的行为来看,str() 采用了分配给它的变量的类型。

str return 类型为 str 的对象。在极少数和不寻常的情况下,它可能 return 是 str 的子类的实例,但绝对不会 return 是您传入的任何类型的对象。

第 2 行在代码片段 2 中通过了类型检查,因为 mypy 有一个 specific special case 表示 str 与 Python 2 上的 unicode 兼容,但反之则不然。