Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

python - 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? 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? 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('
')
field_bool, empty_fields = has_empty_fields()
print("field_bool :", field_bool)
print('
')
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'])
question from:https://stackoverflow.com/questions/65830762/how-to-force-a-function-output-to-be-bool

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to ignore the empty_fields that's returned, you need to explicitly ignore it by binding it to a name like _:

field_bool, _ = has_empty_fields()

If you want weak assurance, and you're on Python 3.5+, you can type hint it:

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. There is no way to enforce it though other than doing run-time type-checking.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...