Custom bool-to-str conversion in f-strings?

Viewed 26

I'm not satisfied with the standard boolean representation, which is "True" or "False". I'd like to see "SUCCESS" and "FAIL" everywhere in my logs. Can I overload the string conversion for boolean variables for my module somehow?

id = 4608
result = False
log(f"Operation {id} status : {result}")

Operation 4608 status : FAIL

1 Answers

Without really overriding the string conversion, you can use the following code to achieve your results

log(f"Operation {id} status : {'SUCCESS' if result else 'FAIL'}")

This would print SUCCESS if result is True and FAIL if its False


Update :

Based on suggestion in comments by @matszwecja, you can always convert it into a function and than just call it, to avoid repetition

def bool_to_string(value: bool) -> str:
    if value:
        return "SUCCESS"
    return "FAIL"

log(f"Operation {id} status : {bool_to_string(result)}")
Related