3 回答

TA贡献1772条经验 获得超8个赞
您可以执行以下操作:
def set_val_type(val, val_type): return eval(val_type + '({})'.format(val))
尽管这似乎是您正在寻找的内容,但不建议使用 eval。正如@pault 之前评论的那样,这似乎是一个 XY 问题

TA贡献1818条经验 获得超3个赞
您可以创建需要处理的所有类型的字典。
def set_val_type(val, val_type):
funcs = {'int': int, 'bool': bool}
return funcs[val_type](val)

TA贡献2065条经验 获得超14个赞
为了避免使用eval,并假设您只使用内置类型,您可以getattr()在内置模块上使用 a (如果您想确保不调用任何函数,您可以执行 an isinstance(user_provided_type_here, type)before。
要允许全局范围内的任何类型,请使用 globals()[user_provided_type_name]
完整示例:
import builtins
def set_val_type(val, val_type);
user_type = getattr(builtins, val_type) # possibly replace with globals()[val_type]
if not isinstance(user_type, type):
raise TypeError(f'{user_type} is no a type.')
return user_type(val)
为什么不使用eval()(使用不受信任的用户输入):
def set_val_type(val, val_type):
return eval(val_type + '({})'.format(val))
evil_val_type = 'bool'
evil_val = 'exec("import os\\nos.chdir(os.path.sep)\\nprint(os.getcwd())")'
print(set_val_type(evil_val, evil_val_name))
'False' # yes, this actually works error-free
有了这种访问级别,一个来自非常坏消息的subprocess.Popen/ 。 也就是说,如果您的用户输入是可信的,则使用是os.system
eval()不是 问题较少。
添加回答
举报