Get type instance from string in Python
<p>So, I need to cast a value to a given type:</p>

<pre><code>if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...
</code></pre>

<p>Is there a way to do that generically? E.g.:</p>

<pre><code>type_instance = get_type_instance(type_name)
value = type_instance(value)
</code></pre>

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

<p><strong>Update:</strong></p>

<p>Here's the solution I'm using:</p>

<pre><code>class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
</code></pre>

<p>This is just a toy parser. <strong>Don't use in production!</strong></p>
