[REQ] Change Python models to not raise exception when unset attribute is accessed
Created by: mks-m
Python models raise exception when accessing an attribute that wasn't set. This leads to very defensive coding style that relies heavily on exceptions for control-flow, which is generally accepted to be bad practice. Until recently it wasn't possible to even check if an attribute is set without accessing internal fields of the model, leading to code like this:
# intended code:
if model.attr:
do_things()
# actual code:
try:
attr = model.attr
except ApiAttributeError:
attr = None
if attr:
do_things()
After #7637 was merged things improved:
# better code:
attr = if 'attr' in model model.attr else None
if attr:
do_things()
However this is still cumbersome compared to the intended code.
I'd like to request that accessing unset attribute no longer raises an exception. There are two potential problems we need to consider:
- What if one needs to differentiate between attribute being unset and attribute being set to actual value
None
?
This is possible thanks to #7637: 'attr' in model and model.attr is None
.
- Backward compatibility: if some projects rely on exception for control-flow we will break their functionality.
We should hide this behavior behind a flag to code generator.
One argument I've heard is that functionality I need is already available when accessing attributes via internal _data_store
field, but to me this is leaking implementation details. In future we may want to change underlying implementation of model's data storage (convert models to Python 3's dataclasses, etc) which will break existing code.
Would such feature be merged if I prepared a PR for it?
cc/ @spacether