0

Example of what I would want to do:

x = 123
TYPE_TO_CONVERT_TO = 'int'

intx = convert(x, TYPE_TO_CONVERT_TO)
4
  • 1
    What is your question and what have you tried? Commented Oct 25, 2018 at 21:05
  • why not int("3434") Commented Oct 25, 2018 at 21:06
  • 2
    if TYPE_TO_CONVERT_TO == 'int': return int(x) ? (assuming you'll implement other types as well). Commented Oct 25, 2018 at 21:06
  • improved TYPES = { t.name : t for t in [int, bool, basestring, float]}; def convert(x, t): return TYPES(t)(x) Commented Oct 25, 2018 at 21:09

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! Kept googling for this info and could not find it! I will try this out! :)
__builtins__ is an implementation detail though. Better use import builtins.
Interesting; did not know that.
Well, I'm not 100% sure if the existence of the __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.
Hmm, it's correct but it's pretty ugly. I think more readable and robust is just to have a whitelist of names/types, like {'int': int, 'float', float}.
0

You can also use:

t = eval(TYPE_TO_CONVERT_TO)
t('123') # => 123

Comments

0

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'

1 Comment

@wim fixed and verified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.