0

I've referred to the following threads and I don't think that this post is a duplicate of any of them:

  1. Calling a function of a module by using its name (a string)
  2. Python Call Function from String
  3. Use a string to call function in Python

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?

ytu
  • 1,822
  • 3
  • 19
  • 42

3 Answers3

6

The best way is still a dictionary, but:

>>> import builtins
>>> getattr(builtins, 'int')
<class 'int'>
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Using a dict is the only sane solution here, period. Not only because it's the most explicit, obvious, readable and maintainable solution but also because you definitly want to have full control when it comes to mapping user inputs (anything that comes from the outside world) to executable code (security 101: never trust user inputs).

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

You can get attributes by names using getattr function:

getattr(obj, 'attr') == obj.attr

So you can use:

import builtins
getattr(builtins, 'int')

But with code like this you cloud get things like input or print, so you should do:

if data_type in ('int',  'float'): 
  getattr(builtins, data_type)
else: 
  raise Exception('...')
Jan Matula
  • 135
  • 1
  • 1
  • 10