Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type instance from string in Python

Tags:

python

So, I need to cast a value to a given type:

if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...

Is there a way to do that generically? E.g.:

type_instance = get_type_instance(type_name)
value = type_instance(value)

I'm using Python 2.7, but would be interested in a Python 3.X solution as well.

Update:

Here's the solution I'm using:

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe

This is just a toy parser. Don't use in production!

like image 299
scribu Avatar asked Aug 29 '12 13:08

scribu


2 Answers

If you need only __builtins__ types you can do

value = getattr(__builtins__, type_name)(value)
like image 98
Alexey Kachayev Avatar answered Oct 01 '22 05:10

Alexey Kachayev


Build a dict

TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
like image 31
Andreas Jung Avatar answered Oct 01 '22 06:10

Andreas Jung