15.04.20 05:59, Raymond Hettinger пише:
SimpleNamespace() is really good at giving attribute style-access. I would like
to make that functionality available to the JSON module (or just about anything
else that accepts a custom dict) by adding the magic methods for mappings so
that this works:
catalog = json.load(f, object_hook=SimpleNamespace)
AFAIK, the only thing required for this is to make SimpleNamespace
accepting a single positional argument: a mapping or a sequence of
key-value pairs. It is easy to do. No new magic methods are needed.
As a workaround you can use
object_hook=lambda x: SimpleNamespace(**x)
print(catalog['clothing']['mens']['shoes']['extra_wide']['quantity'])
# currently possible with dict()
print(catalog.clothing.mens.shoes.extra_wide.quantity]) #
proposed with SimpleNamespace()
It is already possible with SimpleNamespace.
print(catalog.clothing.boys['3t'].tops.quantity
# would also be supported
I would prefer to have a separate class if you want to have attribute
and indexing access in the same object.
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/python-dev@python.org/message/TYIXRGOLWGV5TNJ3XMV443O3RWLEYB65/
Code of Conduct: http://python.org/psf/codeofconduct/