In the spirit for not passing errors silently. I want have a short hand for expressing that a variable will be something eventhough that is coming from an function that returns an optional output and if not it should trigger a RuntimeError. Such that users would have an incentive to embrace defensive design and eliminating the complexity in the code by removing not realistic execution trajectories.
To take a motivating example:
Developer wants write an update user function and writes the following:
def update_user(user_id, **data_to_update):
user = User.query.get(user_id)
user.update(data_to_update)
db.session.commit()
This fails on the on the type checker because User.query.get(user_id)
returns a Optional[User]
Attempting to update a non existing user is something that from the business logic sense newer should happen. So the right thing here would be to trigger a NonImplimentedError. Such that when this for some reason is happening anyway 2 years from now we get it in the error logs.
But since this is so unthinkable at the time of writing a large proportion of developers could tend to the something like following solution to make the static type checker pass:
def update_user(user_id, **data_to_update):
if user := User.query.get(user_id):
user.update(data_to_update)
db.session.commit()
I wish the following was posible
def update_user(user_id, **data_to_update):
user := User.query.get(user_id)
user.update(data_to_update)
db.session.commit()
Which would be translated to:
def update_user(user_id, **data_to_update):
user = User.query.get(user_id)
if user is None:
raise RuntimeError
user.update(data_to_update)
db.session.commit()
I know there is an argument to be made that the current version is more explicit. But I think there should also be put emphasis on nudging users to the currect behavior by making it easy.
I think the walrus operator is a good usage for this since it is a combination of assignment and other operations and it is as far as I can see not used for anything else.
EDIT:
Changing NotImplimentedError to RuntimeError thanks Neil Girdhar and Chris Angelico