Lexical cast from string to type
Question: Recently, I was trying to store and read information from files in Python, and
came across a slight problem: I wanted to read type information from text
files. Type casting from string to int or to float is quite efficient, but
type casting from string to type seems to be another problem. Naturally, I
tried something like this:

    
    
    var_type = type('int')
    

However, `type` isn't used as a cast but as a mechanism to find the type of
the variable, which is actually `str` here.

I found a way to do it with:

    
    
    var_type = eval('int')
    

But I generally try to avoid functions/statements like `eval` or `exec` where
I can. So my question is the following: Is there another pythonic (and more
specific) way to cast a string to a type?


Answer: I like using `locate`, which works on built-in types:

    
    
    >>> from pydoc import locate
    >>> locate('int')
    <type 'int'>
    >>> t = locate('int')
    >>> t('1')
    1
    

...as well as anything it can find in the path:

    
    
    >>> locate('datetime.date')
    <type 'datetime.date'>
    >>> d = locate('datetime.date')
    >>> d(2015, 4, 23)
    datetime.date(2015, 4, 23)
    

...including your custom types:

    
    
    >>> locate('mypackage.model.base.BaseModel')
    <class 'mypackage.model.base.BaseModel'>
    >>> m = locate('mypackage.model.base.BaseModel')
    >>> m()
    <mypackage.model.base.BaseModel object at 0x1099f6c10>
    

