You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中创建TypeGuard确保值非None并通过静态类型检查?

解决Optional[T]非空校验的类型注解与TypeGuard实现

一、正确的类型注解实现

首先修正断言逻辑(原assert val会误判空字符串、0等假值,应明确检查是否为None),再通过泛型TypeVar实现参数化类型注解,确保静态类型检查器能识别返回值已排除None:

from typing import TypeVar, Optional

T = TypeVar("T")

def not_none(val: Optional[T], msg: str) -> T:
    assert val is not None, msg
    return val

使用时直接替代原有断言逻辑即可,类型检查器会自动推导返回值为原Optional[T]中的T类型:

val = not_none(object.data, 'data should not be None')

二、TypeGuard的实现

如果需要在条件分支中让类型检查器自动推导参数类型,可实现TypeGuard函数:

from typing import TypeGuard

def is_not_none(val: Optional[T]) -> TypeGuard[T]:
    return val is not None

它的作用是告知类型检查器:当函数返回True时,参数val的类型为T而非Optional[T]。典型使用场景:

def process_data(data: Optional[str]) -> str:
    if is_not_none(data):
        # 此处data会被识别为str类型,可直接调用字符串方法
        return data.upper()
    raise ValueError("data should not be None")

若仅需代码复用+静态检查,第一种类型注解方案已足够;TypeGuard更适合在条件判断场景中优化类型推导。

内容的提问来源于stack exchange,提问作者link89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:42:23