Le mer. 15 avr. 2020 à 05:02, Raymond Hettinger
<firstname.lastname@example.org> a écrit :
> 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)
> print(catalog['clothing']['mens']['shoes']['extra_wide']['quantity']) # currently possible with dict()
> print(catalog.clothing.mens.shoes.extra_wide.quantity]) # proposed with SimpleNamespace()
> print(catalog.clothing.boys['3t'].tops.quantity # would also be supported
It seems like there are many projects on PyPI which provide such
features. A few examples:
* https://pypi.org/project/attrdict/ "mapping objects that allow their
elements to be accessed both as keys and as attributes"
* https://pypi.org/project/dictlib/ "Dictionary keys as object attributes"
* https://pypi.org/project/objdict/ "An ObjDict supports all normal
dict operations, but adds support for accessing and setting entries as
* https://pypi.org/project/mydict/ "dict subclass which tries to act
access members of the object"
* https://pypi.org/project/dpath/ "accessing and searching
dictionaries via /slashed/paths ala xpath". Example:
There are many variants:
* Support nested dictionaries or not
* "Path" as a string ala XPath using "/" or "." separator -versus-
don't give a direct access into nested dictionaries
* Optional default value when a key/attribute is missing
Is there a project on PyPI which already already been battle-tested
and gained enough popularity to consider that it's now mature enough
to enter the stdlib?
+1 that was my first reaction as well. We don't need this battery.
If you wanted to make it a more general thing, introduce a special operator for it instead of overloading ".". Ex: copy Perl and adopt -> as the "lookup the name in a dictionary without typing quotes around the constant value" operator. (please don't!)
The problem is that so far, I see no clear "winner" of a "standard"
API. So maybe leaving such feature on PyPI is better for now. It seems
like these projects are opinionated about what should be the "right"
And yeah, there are even more advanced tools like https://glom.readthedocs.io/
As I wrote in the issue, I would prefer to leave SimpleNamespace
unchanged. If such feature lands into the stdlib, I would prefer it to
be a new class.
Night gathers, and now my watch begins. It shall not end until my death.
Python-Dev mailing list -- email@example.com
To unsubscribe send an email to firstname.lastname@example.org
Message archived at https://email@example.com/message/XDFTMWK5727ETLVNEANWYN6A3HQN6STT/
Code of Conduct: http://python.org/psf/codeofconduct/