在 python 3.12 之前,我的理解是
mta = int
行创建了一个名为 mta
的类型别名,但在 3.12 中,该行可以(应该?)写为 type mta = int
,即使仍然支持先前的语法。但这些是不可互换的。例如, isinstance
将接受第一个作为合法的第二个参数,但第二个将失败。 (似乎在第二种情况下,isinstance(3, mta.__value__)
有效,但这似乎很尴尬。)
我阅读本文档的意思是,这两种语法都受支持以实现向后兼容性,而不是说它们在功能上有所不同。鉴于这种行为,什么时候使用
type
关键字比较有利?是否存在简单(3.12 之前)分配效果较差的情况?
例如:
>>> mta = int
>>> isinstance(3, mta)
True
>>> type mta = int
>>> isinstance(3, mta)
...
TypeError: isinstance arg 2 must be a type, a tuple of types, or a union