Example of what I would want to do:
x = 123
TYPE_TO_CONVERT_TO = 'int'
intx = convert(x, TYPE_TO_CONVERT_TO)
The type int (and other built-in objects) are in a special namespace (module), which you can access using import builtins. Thus you can do:
intx = getattr(builtins, TYPE_TO_CONVERT_TO)(x)
If you wish to also support types that might be defined in the current module, you can use:
intx = (globals().get(TYPE_TO_CONVERT_TO) or getattr(builtins, TYPE_TO_CONVERT_TO))(x)
The builtins module is also available using __builtins__, but this is an implementation detail. As Aran-Fey points out in a comment, import builtins is the right way to get a reference.
__builtins__ is an implementation detail though. Better use import builtins.__builtins__ variable is an implementation detail, but it is an implementation detail that __main__.__builtins__ is a module object while any_other_module.__builtins__ is a dict. So better not touch it if you don't have to.{'int': int, 'float', float}.You can use the type by themselves as they include __call__ in their implementation.
def func(x, typ):
typ = eval(typ)
return typ(x)
func('12', 'list')
>>> ['1', '2']
func(1, 'str')
>>> '1'
if TYPE_TO_CONVERT_TO == 'int': return int(x)? (assuming you'll implement other types as well).