如何强制函数输出为bool

2024-09-30 20:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的例子中,我如何确保函数总是将“field_bool”输出为bool而不是其他类型? 我想从函数中获取布尔值,并可以选择其他数据(如果需要,可以选择列表),但我想知道哪种方式最适合python,获取列表是field_bool[1]吗?我不知道什么是emu,或者这是否更好

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

Tags: 函数nonetruefieldfields列表settingshead
1条回答
网友
1楼 · 发布于 2024-09-30 20:16:57

如果要忽略返回的empty_fields,则需要通过将其绑定到类似_的名称来显式忽略它:

field_bool, _ = has_empty_fields()

如果您想要弱保证,并且您使用的是Python 3.5+,则可以键入hint it:

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

如果您意外地将元组分配给变量,这将在静态分析过滤器中引起警告。除了执行运行时类型检查之外,没有其他方法可以强制执行它

相关问题 更多 >