我怎样才能编写这段代码,让它适用于给定的每种类型?
def set_val_type(val, val_type):
if val_type == 'bool':
return bool(val)
elif val_type == 'int':
return int(val)
您可以执行以下操作:
def set_val_type(val, val_type):
return eval(val_type + '({})'.format(val))
尽管这似乎是您正在寻找的,但不建议使用 eval。这似乎是一个 XY 问题,正如之前由 @pault
您可以创建需要处理的所有类型的字典。
def set_val_type(val, val_type):
funcs = {'int': int, 'bool': bool}
return funcs[val_type](val)
eval
,并假设您只使用内置类型,您可以在 builtins 模块上使用 getattr()
(如果要确保不调用任何函数,可以先执行isinstance(user_provided_type_here, type)
。
若要允许全局范围内的任何类型,请使用 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()
的问题