blob: 7cb391bbdd2ab25481297a2958f1e2c431fb86c5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
---
tags:
- python
- "#how-to"
references:
- https://docs.python.org/3/library/functions.html#vars
- https://docs.python.org/3/reference/datamodel.html#object.__iter__
---
The `dict` method takes kwargs and creates a dict from that. If we want to pass an object into it the object implement the `__iter__` method.
We can use `vars` to make that easy:
```
def __iter__(self):
for k, v in vars(self):
yield k, v
```
> This only works when all vars are primtiives, a list of objects for example needs nested iteration. Example:
```
yield "volumes", [iter(vol) for vol in self.volumes]
```
|