在下面的例子中,我如何确保函数总是将“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'])
如果要忽略返回的
empty_fields
,则需要通过将其绑定到类似_
的名称来显式忽略它:如果您想要弱保证,并且您使用的是Python 3.5+,则可以键入hint it:
如果您意外地将元组分配给变量,这将在静态分析过滤器中引起警告。除了执行运行时类型检查之外,没有其他方法可以强制执行它
相关问题 更多 >
编程相关推荐