Grant Jenks Logo

Python Tribool Development Notes

The Python Tribool module is the first open-source project I published. As the first, it’s been an interesting learning experience. Python has surprisingly good tools for testing, documentation, and package publishing. From a development standpoint, I wanted to point out two things.

When I began, I assumed it was possible to override the logical operators: and, or, not. Indeed it is possible but not with the built-in and, or, not keywords. Instead, you must use the bit-operators &, |, ^, ~. This was surprising and I’m glad I wrote tests before deploying. Similarly Python provides some dunder methods like __nonzero__, __index__, and __trunc__ which all raise a ValueError. Not implementing __nonzero__ makes an explicit comparison necessary. So rather than writing “if var_tribool:” you should write “if var_tribool.value is True:” That looks a little awkward but I’m thinking explicit is better than implicit.

Also note the design of the implementation: truth-tables. Rather than encoding a series of if, elif, else statements, I use table-lookups to compute results. The implementation is therefore both fast and easily inspected. You could even implement a new operator easily by simply creating a new truth table.

It’s amazing to me than for a project as simple as tribool, there are multiple valid implementations.