检查 Python 变量类型的最佳(惯用)方法是什么? [英] What is the best (idiomatic) way to check the type of a Python variable?
问题描述
我需要知道 Python 中的变量是字符串还是字典.下面的代码有什么问题吗?
I need to know if a variable in Python is a string or a dict. Is there anything wrong with the following code?
if type(x) == type(str()):
do_something_with_a_string(x)
elif type(x) == type(dict()):
do_somethting_with_a_dict(x)
else:
raise ValueError
更新:我接受了 avisser 的回答(尽管如果有人解释为什么 isinstance
比 type(x) is
更受欢迎,我会改变主意)).
Update: I accepted avisser's answer (though I will change my mind if someone explains why isinstance
is preferred over type(x) is
).
但是感谢nakedfanatic提醒我使用dict(作为case语句)比if/elif/else系列更干净.
But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series.
让我详细说明我的用例.如果一个变量是一个字符串,我需要把它放在一个列表中.如果它是一个字典,我需要一个唯一值的列表.这是我想出的:
Let me elaborate on my use case. If a variable is a string, I need to put it in a list. If it's a dict, I need a list of the unique values. Here's what I came up with:
def value_list(x):
cases = {str: lambda t: [t],
dict: lambda t: list(set(t.values()))}
try:
return cases[type(x)](x)
except KeyError:
return None
如果首选 isinstance
,你会如何编写这个 value_list()
函数?
If isinstance
is preferred, how would you write this value_list()
function?
推荐答案
如果有人将 unicode 字符串传递给您的函数会发生什么?还是从 dict 派生的类?或者一个类实现了一个类似 dict 的接口?以下代码涵盖了前两种情况.如果您使用的是 Python 2.6,您可能需要使用 collections.Mapping
而不是 dict
根据 ABC PEP.
What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping
instead of dict
as per the ABC PEP.
def value_list(x):
if isinstance(x, dict):
return list(set(x.values()))
elif isinstance(x, basestring):
return [x]
else:
return None
这篇关于检查 Python 变量类型的最佳(惯用)方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!