3 ms·
Curious to see a small code sample illustrating typical usage of SimpleNamespace if you care to share? Docs didn't include one.
by rattray 7y ago
Curious to see a small code sample illustrating typical usage of SimpleNamespace if you care to share? Docs didn't include one.
- rcfox 7y agoHere's one case I've used it for: foo = json.dumps({'a': 1, 'b': {'c': 2}}) # Pretend you've downloaded some JSON... bar = json.loads(foo, object_hook=lambda x: types.SimpleNamespace(**x)) print(bar.a) print(bar.b.c) print(bar.b.d) # Error bar.b.d = 3 print(bar.b.d) # Works now I mean, you could pretty much do the same sort of thing with namedtuple, except this is mutable and doesn't require a pre-declaration of the keys. It's easier to write off the cuff.