根据其类型使用 Optional[Union[str, int]] 参数中的属性
Use attribute from Optional[Union[str, int]] parameter depending on its type
我有一个参数类型:a: Optional[Union[str, int]]
。
我想在它是字符串时使用一些属性,在它是整数时使用其他属性。
例如:
if type(a) is int:
self.a = a
elif type(a) is str and a.endswith('some prefix'):
self.b = a
但是,MyPy 抱怨如下:
error: Item "int" of "Union[str, int, None]" has no attribute "endswith"
error: Item "None" of "Union[str, int, None]" has no attribute "endswith"
有没有办法让它与 MyPy 一起工作?
您应该使用的习语是 isinstance(a, int)
而不是 type(a) is int
。如果你做前者并写:
if isinstance(a, int):
self.a = a
elif isinstance(a, str) and a.endswith('some_prefix'):
self.b = a
...那么您的代码应该进行干净的类型检查。
之所以 type(a) is int
不是 supported/most 可能不会很快得到支持,是因为你基本上断言 'a' 是 完全是一个int,没有其他类型。
但我们实际上并没有在 PEP 484 中编写这种类型的干净方法——如果你说某个变量 'foo' 是 'Bar' 类型,你真正在说什么'foo' 可以是 'Bar' 或 类型 'Bar'.
的任何子类
我有一个参数类型:a: Optional[Union[str, int]]
。
我想在它是字符串时使用一些属性,在它是整数时使用其他属性。 例如:
if type(a) is int:
self.a = a
elif type(a) is str and a.endswith('some prefix'):
self.b = a
但是,MyPy 抱怨如下:
error: Item "int" of "Union[str, int, None]" has no attribute "endswith"
error: Item "None" of "Union[str, int, None]" has no attribute "endswith"
有没有办法让它与 MyPy 一起工作?
您应该使用的习语是 isinstance(a, int)
而不是 type(a) is int
。如果你做前者并写:
if isinstance(a, int):
self.a = a
elif isinstance(a, str) and a.endswith('some_prefix'):
self.b = a
...那么您的代码应该进行干净的类型检查。
之所以 type(a) is int
不是 supported/most 可能不会很快得到支持,是因为你基本上断言 'a' 是 完全是一个int,没有其他类型。
但我们实际上并没有在 PEP 484 中编写这种类型的干净方法——如果你说某个变量 'foo' 是 'Bar' 类型,你真正在说什么'foo' 可以是 'Bar' 或 类型 'Bar'.
的任何子类