Lexical cast from string to type

前端 未结 4 998
粉色の甜心
粉色の甜心 2020-12-01 09:26

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

4条回答
  •  -上瘾入骨i
    2020-12-01 09:41

    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()
    
    

提交回复
热议问题