I have a use case in which I need to check whether a given value is explicitly True
or False
:
def stringify(value):
"""Returns the string representation of the value."""
if value is None:
return '-'
if value is True:
return '✓'
if value is False:
return '✗'
return str(value)
I know, that in most cases, where you just need the truthiness, you'd just do if value:
. But here this will not suffice, since I want zero int
s and float
s to be displayed in their decimal form as well as empty list
s, set
s dict
s as such.
Is the above code acceptable or should I rather check using isinstance(value, bool)
first and then do if value:
?
What's the least surprising way to go?
Usage Context
The function is part of an API that converts database records to terminal output:
MariaDB → peewee → API → terminal
Example output:
$ termutil ls -T 1000
ID TID CID VID OS IPv4 Address Deployed Testing Tainted Address Annotation
214 1 1000 - HIDSL latest XX.Y.Z.75 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
215 2 1000 - HIDSL latest XX.Y.Z.76 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
216 3 1000 - HIDSL latest XX.Y.Z.77 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
217 4 1000 - HIDSL latest XX.Y.Z.78 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
218 5 1000 - HIDSL latest XX.Y.Z.79 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
219 6 1000 - HIDSL latest XX.Y.Z.80 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
330 7 1000 399 HIDSL latest XX.Y.Z.182 - ✗ ✗ Musterstraße 42, 123456 Irgendwo -
508 8 1000 - HIDSL latest XX.Y.Z.189 - ✗ ✗ N/A -
[]
→"[]"
and"[]"
→"[]"
etc. \$\endgroup\$