Skip to content

Instantly share code, notes, and snippets.

@letam
Created December 29, 2019 03:17
Show Gist options
  • Save letam/025493feee14b36f0295a99f76be532a to your computer and use it in GitHub Desktop.
Save letam/025493feee14b36f0295a99f76be532a to your computer and use it in GitHub Desktop.
Utility to return the specified fields of an object as a dict with fields mapped to values. Handles nested attribues specified by '__' delimiter. For JSON and stuff.
from typing import List, Union, Tuple, Dict, Any
def nestedattr(obj: object, field: str):
if "__" in field:
primary_field, remainder_field = field.split("__", 1)
primary_field_value = getattr(obj, primary_field)
if not primary_field_value:
return primary_field_value
return nestedattr(primary_field_value, remainder_field)
else:
return getattr(obj, field)
def obj_to_dict(
obj: object, fields: List[Union[Tuple[str, str], str]]
) -> Dict[str, Any]:
"""Return the specified fields of an object as a dict with fields mapped to values.
Handles nested attribues specified by '__' delimiter.
For JSON and stuff.
"""
return {
(field if type(field) == str else field[1]): nestedattr(
obj, (field if type(field) == str else field[0])
)
for field in fields
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment