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

如何将表示Python数据类型的字符串转为实际类型以校验变量类型

实现方法

首先明确核心逻辑:需要先把类型名称的字符串映射为对应的Python类型对象,再进行类型校验。

原有代码返回False的核心原因是:dtype是字符串类型值,而type(x)返回的是对应数据的类型对象,二者类型不同自然无法相等。


方法1:直接从内置命名空间获取类型(适合内置标准类型场景)

Python所有内置类型都存放在__builtins__内置命名空间中,可通过getattr直接获取对应类型对象:

dtype = 'str'
x = 'hello'

# 从内置空间获取类型对象
target_type = getattr(__builtins__, dtype)
# 校验类型,isinstance兼容继承场景
result = isinstance(x, target_type)
print(result) # 输出 True

如果需要严格校验类型完全一致(不接受子类实例),可以替换为:

result = type(x) == target_type

方法2:手动维护类型映射表(更安全,推荐生产环境使用)

如果类型名称是外部可控输入,直接调用__builtins__存在安全风险,也可能获取到非类型的内置对象,因此手动维护映射表更可控:

# 按需定义支持校验的类型映射
ALLOWED_TYPES = {
    'str': str,
    'int': int,
    'float': float,
    'list': list,
    'dict': dict,
    'bool': bool,
    'tuple': tuple
}

dtype = 'str'
x = 'hello'

target_type = ALLOWED_TYPES[dtype]
result = isinstance(x, target_type)
print(result) # 输出 True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:33:03