Use case: When we are querying from an API, the JSONs can be very nested and can get messy. Here's what I mean:
json["field"]["field1"]["field2"] # Messy!# What about this instead?json.field.field1.field2 # Not messy :)
Example:
# pip install attrdictfrom attrdict import AttrDict# json: dictjson =AttrDict(json)json.field.field1.field2 # possible now
Extension:
We can use a dataclass like so to make this even cleaner.
from dataclasses import dataclassfrom dataclasses import fieldimport operatorfrom attrdict import AttrDict@dataclassclassExampleClass: a:str=field(metadata={"api_key": "field1"}) b:str=field(metadata={"api_key": "field1.field2.field3"})json = request.get(...).json()json =AttrDict(json)for field infields(ExampleClass): api_key = field.metadata["api_key"]# Can do this: api_value = operator.attrgetter(api_key)(json)# OR this: api_value =eval(f"json.{api_key}")# Both of these probably need try-excepts for AttributeError