Introducing a Safe Navigation Operator in Python

if expression checks if the expression is truthy, whereas if not expression checks if the expression is falsy.

By definition, None is an object frequently used to represent the absence of a value. If a user chooses to rely on a somewhat vague distinction between the absence of a value and an empty value, it can make coding more complicated by requiring explicit checks to determine if a given value or attribute is None, as you demonstrated. Technically, though, you are correct.

However, you can be more explicit when handling empty values:

obj = {'a': 2}
# obj = {}
# obj = None

if obj and (keys := set(obj.keys())):
    print(keys)

else:
    print('Empty:', set())

if obj is not None and (keys := set(obj.keys())):
    print(keys)

else:
    print('Empty:', set())

I don’t see any added value in using optional variables. Using Optional makes falsy values redundant. But, ultimately, it comes down to code style.


Current language features do not favor the extensive use of None. However, if a None-aware operator were introduced, it would make working with optional variables much easier. You might be interested in the new thread discussing a similar proposal.

If the moderators agree, this thread may be closed.