Skip to main content

Trinary state variables

Created
Active
Viewed 28 times
0 replies
0
2 votes
3 answers
212 views

Checking for False when variable can also be None or True

Update: please see my discussion if you want to delve further into this topic! Thank you everyone for your feedback on this! I have a boolean(ish) flag that can be True or False, with None as an ...
AutumnKome's user avatar

I wanted to delve further into the topic of trinary state variables and get some feedback on implementing them the "proper" way.

Issue:

I am using a custom dict class with items moved to attributes (specifically to make it easier to get the uninitialized state). Initialized attributes have a default value of None, no matter what the attribute type is (bool, str, float, int, tk.Widget, other custom class, etc).

I have been using the None state as a False equivalent for bool types, as it's easy enough to check for None vs True. However, the option to add False was a bit too tempting and I started using trinary state variables in some cases (a couple of flags).

I have since switched to using multiple flags as needed to avoid the trinary state operator.

Question:

When using an explicit default value of None for all variables types, when I check for an initialized vs uninitialized value, I typically check for:

# None checking for initialized values:
if mydict.value is None:
    print("value is not initialized")
if value is not None:
    print("value is initialized")

# Versus state checking:
if not value:
    print("value might not be initialized")
    # not valid for bool, int, float, empty string
if value:
    print("value is initialized")
    # not valid for certain types which don't have __eq__ implemented?
    # Should I implement __eq__ for these types?
    # Or continue to rely on None checking?

It was recommended in my Question accepted Answer to move to using known defaults for each type, but this isn't going to be feasible as it would likely require @property implementation for a total revamp of my attribute setter/getter.

None checking is generally usable for all of the data types, whereas state checking does not appear to be implemented for all of the data types I am using. Furthermore, state checking isn't a valid method of checking uninitialized str or number types in certain cases (where '' is a valid string or 0is a valid number).

Should I continue to rely on None checking or try to move toward state checking?

If I do move toward state checking, I would need to do some thorough testing and add comments where I do need to check for None instead of is value/is not value.

Looking for ideas, thanks!