0

How do I convert a class name to a class constructor ?

Example

Let say we have a method that takes two strings as input, first the output type, and then the value to convert. Here are some example of outputs:

  • foo("int", "12") would return 12
  • foo("str", "12") would return "12"
  • foo("float", "12") would return 12.0

What is the content of foo(), without using pydoc.locate() ?

edit: getattr(sys.modules[name], str) works with new classes, but not with systems classes. Then it's not a valid solution for my problem

jeandemeusy
  • 226
  • 3
  • 12
  • `eval(...)` or `ast.literal_eval(...)` with security measures. Or rethink your approach without strings. – Jan Oct 18 '21 at 11:23
  • Have you consider passing int/str/float argument as a class instead of a string? – blazej Oct 18 '21 at 11:24
  • 1
    `import builtins; getattr(builtins, 'int')('12')` – deceze Oct 18 '21 at 11:26
  • Thanks @deceze ! That is working perfectly ! – jeandemeusy Oct 18 '21 at 11:34
  • Sanely you should have a dict `{'int': int, ...}` from which you can easily convert string values to classes and prevent arbitrary classes from being used. If you're just after builtins, you can use the `builtins` module as shown above, but that includes access to `eval`, and at that point, you may indeed just use `eval` directly… – deceze Oct 18 '21 at 11:34

0 Answers0