Proposal: SimpleNamespace "recursive" parameter

David Rashty rashtyda at gmail.com
Thu Aug 13 03:04:32 EDT 2020


It would be nice if you could do this to create a "nested" SimpleNamespace:
>>> d = {"_meta": {"fields": ({"name": "field0"}, {"name": "field1"})}}
>>> sns = SimpleNamespace(**d)
>>> print(sns._meta.fields[0].name)  # This is what I wish you could do
'field0'

SimpleNamespace does this though:
>>> d = {"_meta": {"fields": ({"name": "field0"}, {"name": "field1"})}}
>>> sns = SimpleNamespace(**d)
>>> print(sns._meta)  # Python 3.8
{"fields": ({"name": "field0"}, {"name": "field1"})}

I'd love to add a "recursive" parameter to SimpleNamespace to do as above i.e.,
>>> d = {"_meta": {"fields": ({"name": "field0"}, {"name": "field1"})}}
>>> sns = SimpleNamespace(recursive=True, **d)
>>> print(sns._meta.fields[0].name)  # Proposal
'field0'

My current use case is to mock out a Django model in a more straightforward fashion than using unittest.mock.Mock.

Does anyone else here think this is a good idea?

Refs:
https://gist.github.com/pandichef/d3cc137036a7be0c29e9afb27bfbf55e
https://stackoverflow.com/questions/38034377/object-like-attribute-access-for-nested-dictionary/63389458#63389458
https://greenash.net.au/thoughts/2017/08/using-pythons-namedtuple-for-mock-objects-in-tests/


More information about the Python-list mailing list