在python 3.10中,使用typing.typeguard可以精确收窄类实例类型。具体做法是定义一个返回类型为typeguard[targetclass]的函数,并在该函数内部通过逻辑判断(如检查属性或调用方法)来验证实例是否属于目标类型。当使用该函数作为条件时,静态类型检查器(如mypy)会将变量在该作用域内自动窄化为targetclass,从而允许访问其特有属性和方法。

TypeGuard与isinstance的区别是什么?
TypeGuard允许自定义复杂的类型检查逻辑,而不仅仅是基于类的继承关系。它适用于需要检查多个条件、非标准类型或动态属性的场景。相比之下,isinstance仅能基于类进行简单的类型匹配。

from typing import TypeGuard, Union
class Dog:
def __init__(self, name: str):
self.name = name
def bark(self) -> str:
return "Woof!"
class Cat:
def __init__(self, name: str):
self.name = name
def meow(self) -> str:
return "Meow!"
def is_dog(pet: Union[Dog, Cat]) -> TypeGuard[Dog]:
# 假设我们通过某种方式(如检查特定属性或外部数据)来判断
# 这里简化为检查是否有 'bark' 方法且名称不为空
return hasattr(pet, 'bark') and isinstance(pet, Dog)
def process_pet(pet: Union[Dog, Cat]):
if is_dog(pet):
# pet 在这里被窄化为 Dog
print(f"{pet.name} says {pet.bark()}")
else:
# pet 在这里被窄化为 Cat
print(f"{pet.name} says {pet.meow()}")
# 测试
dog = Dog("Buddy")
cat = Cat("Whiskers")
process_pet(dog)
process_pet(cat)
预期输出:
Buddy says Woof!
Whiskers says Meow!
如何处理嵌套对象中的类型收窄?
在处理包含多个可能类型的嵌套结构时,TypeGuard同样有效。例如,如果一个列表中包含不同类型的对象,可以使用TypeGuard函数来过滤和识别特定类型的元素,从而在后续代码中安全地访问其成员。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

from typing import TypeGuard, List, Union
class Button:
def click(self) -> None:
print("Button clicked")
class Slider:
def adjust(self) -> None:
print("Slider adjusted")
def is_button(widget: Union[Button, Slider]) -> TypeGuard[Button]:
return isinstance(widget, Button)
def interact_with_widgets(widgets: List[Union[Button, Slider]]):
for widget in widgets:
if is_button(widget):
# widget 被窄化为 Button
widget.click()
else:
# widget 被窄化为 Slider
widget.adjust()
# 测试
widgets = [Button(), Slider(), Button()]
interact_with_widgets(widgets)
预期输出:
Button clicked
Slider adjusted
Button clicked
如果TypeGuard函数返回False,类型会如何变化?
当TypeGuard函数返回False时,类型检查器不会将变量窄化为目标类型,而是保持其原始联合类型或将其窄化为排除目标类型后的剩余类型。这意味着在if not is_guard(...)分支中,你可以安全地假设变量不属于目标类型,但仍需确保它在其他可能的类型范围内。
from typing import TypeGuard, Union
class A:
pass
class B:
pass
def is_a(obj: Union[A, B]) -> TypeGuard[A]:
return isinstance(obj, A)
def handle_obj(obj: Union[A, B]):
if is_a(obj):
# obj 是 A
pass
else:
# obj 是 B (因为如果是A,上面已经处理了)
# 注意:这里obj的类型被推断为B,前提是A和B是仅有的两种可能
pass
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










