(split from PEP 505: status?)
These proposals look very interesting. As said above, ?.
exists in many languages and it’s very useful.
The ability to short-circuit property access if it does not exist would be useful in many cases. For instance
def foo(logger: logging.Logger | None, **kwargs):
# bunch of stuff
if logger is not None:
logger.info("a bunch of stuff was done")
# some other stuff
if logger is not None:
logger.info("some other stuff was done")
Having these checks every time seems wasteful in space hindering readability.
I could go around it by creating a proxy object or a function, but that creates more surface for not much in my opinion.
On the other hand the following code
def foo(logger: logging.Logger | None, **kwargs):
# bunch of stuff
logger?.info("a bunch of stuff was done")
# some other stuff
logger?.info("some other stuff was done")
Is readable to anybody.
This is even more true for nested checks
class Bar:
baz: Callable[[], str] | None
class Foo:
bar: Bar | None
# current
foo: Foo | None = ...
value: str | None = None
if (
foo is not None
and foo.bar is not None
and foo.bar.baz is not None
):
value = foo.bar.baz()
# idea
value: str | None = foo?.bar?.baz?()
If None is not “special” enough, why not extend to any object as an “optional” attribute getter like so?
class Foo:
foo: X
class Bar:
bar: Y
value: Foo | Bar = ...
result: X | None = value?.foo
So we’d have some sort of __getoptattr__(self, name)
that would return None if the attribute does not exist.
Has this been proposed before?