如何强制函数输出为布尔值

How to force a function output to be bool

在下文中,我如何确保函数始终输出 'field_bool' 作为 bool 而不是任何其他类型? 我想从函数中获取布尔值,并可以选择其他数据(如果需要的话,列表)但我想知道哪种方式是最pythonic的方式,它会是 field_bool[1] 来获取列表吗?我不确定动车组是什么,或者动车组是否更好?

def has_empty_fields():
    head_settings_dict = {"ColourRecall" : None, "HeightRecall" : 6000,"TintRecall" : -1, "ViRecall" : 1.3,"Vi_Tint1" : 2.2, "Vi_Tint2" : 3.3}
    empty_fields = []
    for k,v in head_settings_dict.items():             
        #print(k,v)
        if v is None:
            #print("SETTINGS ERROR:", k +" is an empty field!")
            field_bool = True
            empty_fields.append(k)
        if v == -1:
            #print("SETTINGS ERROR:",k, "Field not programmed!")
            field_bool = True
            empty_fields.append(k)
    return field_bool, empty_fields

print("has_empty_fields() :", has_empty_fields())
print('\n')
field_bool, empty_fields = has_empty_fields()
print("field_bool :", field_bool)
print('\n')
field_bool = has_empty_fields()
print("field_bool :", field_bool)

回溯

has_empty_fields() : (True, ['ColourRecall', 'TintRecall'])


field_bool : True


field_bool : (True, ['ColourRecall', 'TintRecall'])

如果您想忽略返回的 empty_fields,您需要通过将其绑定到 _:

这样的名称来显式忽略它
field_bool, _ = has_empty_fields()

如果您想要弱保证,并且您使用的是 Python 3.5+,您可以输入提示:

field_bool: bool = has_empty_fields()[0]  # [0] to get the first element of the tuple

如果您不小心将元组分配给变量,这将在静态分析 linter 中引起警告。除了进行 运行 时间类型检查外,没有其他方法可以强制执行它。