Add public BaseModel.iter() method
See original GitHub issueFeature Request
Add BaseModel.iter()
method which will behave exactly like a dict, but without converting nested values to dict by default and will be a generator instead
Why
Imagine you want to iterate through values in model, but also need to exclude some, or use aliases instead of attributes. So what you need to do is write something like this:
for attr, value in model.dict(exclude={...}, by_alias=True).items():
do_something(attr, value)
Obviously, in this case python will firet evaluate model.dict(exclude={...}, by_alias=True).
part, going through all values and only then you will be able to iterate, going through the same values again.
Also, by using dict nested values are force-converted to dict, and this might be very slow when we just want to iterate through top-level values.
We also cannot use existing _iter()
, because some work is actually done in dict()
How we can solve it
By having iter()
method we can bypass this double-iteration problem and converting-to-dict problems:
for attr, value in model.iter(exclude={...}, by_alias=True):
do_something(attr, value)
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (6 by maintainers)
This already exists!
It’s called
._iter()
.For what it’s worth, I would be in favor of moving logic from
dict
into_iter
, assuming it didn’t result in meaningful performance penalties in any public methods – I think it would simplify/result in a smaller diff for the implementation ofdump_as_type
from #812, and the related serialization performance improvements (even when not dumping as a specified type).