相关疑难解决方法(0)

检查Python变量类型的最佳(惯用)方法是什么?

我需要知道Python中的变量是字符串还是字典.以下代码有什么问题吗?

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
Run Code Online (Sandbox Code Playgroud)

更新:我接受了avisser的回答(但如果有人解释为什么isinstance更喜欢,我会改变主意type(x) is).

但由于nakedfanatic提醒我,这是经常清洁剂使用的字典(作为case语句)比如果/ elif的/其他系列.

让我详细说明我的用例.如果变量是一个字符串,我需要将它放在一个列表中.如果它是一个字典,我需要一个唯一值的列表.这是我想出的:

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
Run Code Online (Sandbox Code Playgroud)

如果isinstance是首选,你会怎么写这个value_list()功能?

python types typechecking

296
推荐指数
6
解决办法
33万
查看次数

类型检查参数Python

有时需要在Python中检查参数.例如,我有一个函数接受网络中其他节点的地址作为原始字符串地址或接收封装其他节点信息的类Node.

我使用type(0函数,如:

    if type(n) == type(Node):
        do this
    elif type(n) == type(str)
        do this
Run Code Online (Sandbox Code Playgroud)

这是一个很好的方法吗?

更新1: Python 3具有函数参数的注释.这些可用于使用工具进行类型检查:http://mypy-lang.org/

python typechecking

39
推荐指数
5
解决办法
8万
查看次数

标签 统计

python ×2

typechecking ×2

types ×1