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
I like using locate
, which works on built-in types:
>>> from pydoc import locate
>>> locate('int')
>>> t = locate('int')
>>> t('1')
1
...as well as anything it can find in the path:
>>> locate('datetime.date')
>>> d = locate('datetime.date')
>>> d(2015, 4, 23)
datetime.date(2015, 4, 23)
...including your custom types:
>>> locate('mypackage.model.base.BaseModel')
>>> m = locate('mypackage.model.base.BaseModel')
>>> m()