简体   繁体   English

如何强制 function output 为布尔型

[英]How to force a function output to be bool

In the following how can I make sure the function is always outputting 'field_bool' as a bool and not anything other type?在下文中,如何确保 function 始终将“field_bool”输出为 bool 而不是其他类型? I wanted to get the boolean value from the function and have the option of the other data (the list if need be) but I am wondering which would be the most pythonic way, would it be field_bool[1] to get the list?我想从 function 中获取 boolean 值,并可以选择其他数据(如果需要,可以选择列表),但我想知道哪一种是最 Pythonic 的方式,它会是field_bool[1]来获取列表吗? im not sure what an emu is or if that would be better?我不确定鸸鹋是什么,或者那样会更好吗?

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)

Traceback追溯

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


field_bool : True


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

If you want to ignore the empty_fields that's returned, you need to explicitly ignore it by binding it to a name like _ :如果您想忽略返回的empty_fields ,您需要通过将其绑定到类似_的名称来显式忽略它:

field_bool, _ = has_empty_fields()

If you want weak assurance, and you're on Python 3.5+, you can type hint it:如果您想要弱保证,并且您使用的是 Python 3.5+,您可以输入提示:

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

This will cause a warning in static analysis linters if you accidentally assign a tuple to the variable.如果您不小心将元组分配给变量,这将在 static 分析 linter 中导致警告。 There is no way to enforce it though other than doing run-time type-checking.除了进行运行时类型检查之外,没有办法强制执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM