Skip to content

Instantly share code, notes, and snippets.

@sairamkrish
Last active August 24, 2023 23:25
Show Gist options
  • Save sairamkrish/ab68be93b53b34c98e24908c67dfda0d to your computer and use it in GitHub Desktop.
Save sairamkrish/ab68be93b53b34c98e24908c67dfda0d to your computer and use it in GitHub Desktop.

Revisions

  1. sairamkrish renamed this gist Jan 23, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. sairamkrish created this gist Jan 23, 2019.
    26 changes: 26 additions & 0 deletions object_to_dict_recursive
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    '''
    Generic object to dict converter. Recursively convert.
    Useful for testing and asserting objects with expectation.
    '''

    def todict(obj, classkey=None):
    if isinstance(obj, dict):
    data = {}
    for (k, v) in obj.items():
    data[k] = todict(v, classkey)
    return data
    elif hasattr(obj, "_ast"):
    return todict(obj._ast())
    elif hasattr(obj, "__iter__") and not isinstance(obj, str):
    return [todict(v, classkey) for v in obj]
    elif hasattr(obj, "__dict__"):
    data = dict([(key, todict(value, classkey))
    for key, value in obj.__dict__.items()
    if not callable(value) and not key.startswith('_')])
    if classkey is not None and hasattr(obj, "__class__"):
    data[classkey] = obj.__class__.__name__
    return data
    elif isinstance(obj, datetime):
    return obj.strftime("%Y-%m-%d %H:%M:%S%z")
    else:
    return obj