I've referred to the following threads and I don't think that this post is a duplicate of any of them:
For instance, assume that I have a string, data_type = "int"
, and I want to call the built-in function int
directly with the string. BTW I cannot have data_type = int
because data_type
is actually loaded from a JSON file, i.e. data_type
is always a string or None
.
My best (neatest) attempt is eval(data_type)("4")
, but as people suggested, eval
doesn't seem to be a good option and should be avoided whatever.
An alternative is creating a dictionary like data_type_dic = {"int": int, "float": float}
and executing data_type_dic[data_type]("4")
. However, creating that dictionary feels like "reinventing the wheel" to me.
Since int
is a built-in function, not a method in a module, so getattr
seems unworkable. It is not a self-defined function either, so locals()[data_type]
gives KeyError
.
What is the best way to call a built-in function with the corresponding string then?
The best way is still a dictionary, but:
>>> import builtins
>>> getattr(builtins, 'int')
<class 'int'>