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

如何将变量转为UUID(已是UUID则无操作)以实现正确比较

解决方案

可以写一个极简的辅助函数来统一类型,既处理字符串转UUID的情况,又保留已有的UUID实例:

import uuid

def to_uuid(val):
    return val if isinstance(val, uuid.UUID) else uuid.UUID(val)

之后用这个函数包装不确定类型的变量,就能放心比较了:

if for_sure_a_uuid != to_uuid(uuid_as_an_str_or_uuid):
    raise Exception("not the right UUID")

如果不想单独写函数,也可以用一行条件表达式完成转换:

target = uuid_as_an_str_or_uuid if isinstance(uuid_as_an_str_or_uuid, uuid.UUID) else uuid.UUID(uuid_as_an_str_or_uuid)
if for_sure_a_uuid != target:
    raise Exception("not the right UUID")

这种方式既避免了冗余的类型判断代码,又能确保两边都是UUID实例,比较逻辑完全可靠。

内容的提问来源于stack exchange,提问作者Greg St. Onge

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:19:51