查找对象可以转换为哪些其他python类型?

时间:2016-01-07 10:19:18

标签: python

作为一个简单的例子,假设一个实用方法,它接受一个python对象input_obj和一个out_type,一个python type来转换(强制转换)该对象

def convert_obj(input_obj,out_type):

-examples

convert_obj('2','int')
#returns 2
convert_obj([1,2,3],'tuple')
#returns (1,2,3)

该方法仅支持特定类型的对象,如str,list,tuple,然后检查是否可以将其转换为指定的out_type。 这是方法中的规则手册:

 supported_conversions = {
       tuple: [str, list, set],
       str: [tuple, float, list, long, int, set],
       float: [str, long, int],
       list: [tuple, str, set],
       long: [str, float, int],
       dict: [tuple, str, list, set],
       int: [str, float, long],
       set: [tuple, str, list],

    }

supported_conversions中的键是input_obj的允许类型。

问题:除了在所有可能的python类型的列表上使用try / except来转换每种类型的示例对象,然后查看有效的内容, 例如检查{list,dict,tuple,int,tuple,set]的str转换 有没有更好的方法在python中生成dict supported_conversions,给定它的键?

注意:要忽略类型转换的其他异常。例如 “1”可以转换为整数1,但“XYZ”不能。但这还是 表示str-> int是有效的可能转换。

1 个答案:

答案 0 :(得分:3)

我认为问题空间的定义不足以使这种方法存在。 一些转换将具有破坏性,有些可能以多种方式发生。几个例子:

>>> list(set([1,2,2,3]))
[1, 2, 3]
>>> list("hello")
['h', 'e', 'l', 'l', 'o']
>>> ["hello"]
['hello']
>>> list({'a':1, 'b': 2})
['a', 'b']
>>> list({'a':1, 'b': 2}.iteritems())
[('a', 1), ('b', 2)]

为了参数,您还可以使用eval()将字符串转换为基本上任何Python类型。

所以,基本上,这完全取决于你的用例。

如果您真的想要进行更详尽的搜索,可以使用types模块获取内置类型列表,然后尝试交叉转换(假设您可以获取每个类型的实例)这些):

>>> import types
>>> [types.__dict__.get(t) for t in dir(types) if t.endswith('Type')]
[<type 'bool'>, <type 'buffer'>, <type 'builtin_function_or_method'>, <type 'builtin_function_or_method'>, <type 'classobj'>, <type 'code'>, <type 'complex'>, <type 'dictproxy'>, <type 'dict'>, <type 'dict'>, <type 'ellipsis'>, <type 'file'>, <type 'float'>, <type 'frame'>, <type 'function'>, <type 'generator'>, <type 'getset_descriptor'>, <type 'instance'>, <type 'int'>, <type 'function'>, <type 'list'>, <type 'long'>, <type 'member_descriptor'>, <type 'instancemethod'>, <type 'module'>, <type 'NoneType'>, <type 'NotImplementedType'>, <type 'object'>, <type 'slice'>, <type 'str'>, <type 'traceback'>, <type 'tuple'>, <type 'type'>, <type 'instancemethod'>, <type 'unicode'>, <type 'xrange'>]

我不知道您是否需要事先生成supported_conversions词典。假设您始终将intype转换为outtype outtype(intype_value),您可以尝试,然后更新映射(intype, outtype) -> bool的词典,这样就不会尝试转换如果它第一次失败了又一次。

相关问题