Adding to this, conditionally omitting arguments, would probably become more frequent when sentinel
s are included in std. Let’s say I have authored a library function with a (intended to be) super secret sentinel that I do not want others to use, e.g. _MISSING
, how does a user provide argument to this parameter conditionally?
# mylib.py
_NOT_GIVEN = object() # replace with sentinellib when avaialble
def foo(x, *, y = _NOT_GIVEN, z):
...
Current ways:
# app.py
# method 1
from mylib import foo, _NOT_GIVEN # problematic
foo(x, y=y if condition else _NOT_GIVEN, z=z)
# method 2
# most obvious but verbose
if cond:
foo(x, y=y, z=z)
else:
foo(x, z=z)
# method 3
# this is one class of problem the proposed method solves
# but even this could be difficult with complex signatures, e.g.
# def foo(a, b=s1, /, c=s2, *, d=s3, e): ...`
kwargs = {"z": z}
if cond:
kwargs |= {"y": y}
foo(x, **kwargs)
Whereas, the most natural form would be:
foo(x, y=y if cond, z=z)
# or
foo(
x,
y=y if cond,
z=z,
)
This generalizes to complex signatures equally well, and makes it more readable IMO.
# def foo(a, b=s1, /, c=s2, *, d=s3, e): ...
foo(
a,
b if cond1,
c = c if cond2,
d = d if cond3,
e=e,
)