How can I write this code so it works for every type given?
def set_val_type(val, val_type):
if val_type == 'bool':
return bool(val)
elif val_type == 'int':
return int(val)
How can I write this code so it works for every type given?
def set_val_type(val, val_type):
if val_type == 'bool':
return bool(val)
elif val_type == 'int':
return int(val)
You can do something like:
def set_val_type(val, val_type):
return eval(val_type + '({})'.format(val))
As much as this seems to be what you are looking for, using eval is not recommended. It seems like an XY problem as commented before by @pault
You can create a dictionary of all the types you need to process.
def set_val_type(val, val_type):
funcs = {'int': int, 'bool': bool}
return funcs[val_type](val)
To avoid using eval
, and presuming you are only using builtin types, you can use a getattr()
on the builtins module (if you want to make sure you don't call any functions, you can perform an isinstance(user_provided_type_here, type)
before.
To allow any type in global scope, use globals()[user_provided_type_name]
Complete example:
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)
Why not to use eval()
(with untrusted user input):
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
With this level of access, one is just a subprocess.Popen
/ os.system
from very bad news.
That said, if your user input is trusted, using eval()
is not less problematic.