从字符串到类型的词法转换 [英] Lexical cast from string to type

查看:104
本文介绍了从字符串到类型的词法转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我试图在Python中存储和读取文件中的信息,并遇到一个小问题:我想从文本文件读取类型信息。从字符串到int或float的类型转换是相当高效的,但类型转换从字符串到类型似乎是另一个问题。当然,我尝试这样的:

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

但是,类型不用作转型,而是用作查找类型的机制的变量,这实际上是 str 这里。

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

我发现了一种方法:

var_type = eval('int')

$ b b

但我通常尝试避免像 eval exec 。所以我的问题是:是否有另一种蟒蛇(更具体)的方式来将字符串转换为类型?

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?

推荐答案

我喜欢使用 locate ,它适用于内置类型:

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

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

...在路径中:

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

这篇关于从字符串到类型的词法转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆