[Python-ideas] PEP 505: None-aware operators

James Lu jamtlu at gmail.com
Wed Jul 25 21:12:14 EDT 2018


What if we used ? after the statement beginning?

name ?= person.name
custom_query ?= entity.get_query(context)
# Becomes None if entity is None. Raise an exception if entity is not None and get_query is None or undefined.
custom_query ??= entity.get_query(context)
# If entity, entity.get_query, entity.get_query(context) evaluate to null, the operation short-circuits and custom_query becomes None
await? foo
with? bar as baz:
    # this only runs if bar is not None
    pass


?= only short circuits into None when the first evaluation is None (the weak operator)
??= short circuits into None whenever any evaluation is None or raises an AttributeError. (the strong operator)

I’m imagining the strong operator would be useful especially for duck typing. No more hasattr checks, no more isinstance checks. 

I would like to see some real world use cases for none aware operators that couldn’t be covered by these none aware assignment operators.

Previous code:
# original code
a ?= b.c
# another, second, programmer comes along and changes it to
a ?= b.c.d

The interpreter would raise an exception, if “d” was None or not defined on “c”. If this is intended behavior, this forces the second programmer to explicitly mark that all attribute access is coalescing with the strong operator, instead of the interpreter swallowing the exception now and emitting an exception later. The previous code assumes “b” is None, which in reality may represent the state of a network socket or a file transfer. The program may display that the operation was complete, leading to a bug in the output. 

I believe this is more readable as well.
> On Jul 25, 2018, at 7:32 PM, python-ideas-request at python.org wrote:
> 
> PEP 505: None-aware operators


More information about the Python-ideas mailing list