It has been asked: How to initialize a SimpleNamespace from a dict?
My question is for the opposite direction. How to initialize a dict from a SimpleNamespace?
It has been asked: How to initialize a SimpleNamespace from a dict?
My question is for the opposite direction. How to initialize a dict from a SimpleNamespace?
from types import SimpleNamespace
sn = SimpleNamespace(a=1, b=2, c=3)
vars(sn)
# returns {'a': 1, 'b': 2, 'c': 3}
sn.__dict__
# also returns {'a': 1, 'b': 2, 'c': 3}
The straightway dict wont work for heterogeneous lists.
import json
sn = SimpleNamespace(hetero_list=['aa', SimpleNamespace(y='ll')] )
json.loads(json.dumps(sn, default=lambda s: vars(s)))
This is the only way to get back the dict.