Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions knack/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,22 +54,27 @@ def to_snake_case(s):
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()


def todict(obj): # pylint: disable=too-many-return-statements

def todict(obj, post_processor=None): # pylint: disable=too-many-return-statements
"""
Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process
"""
if isinstance(obj, dict):
return {k: todict(v) for (k, v) in obj.items()}
result = {k: todict(v, post_processor) for (k, v) in obj.items()}
return post_processor(obj, result) if post_processor else result
elif isinstance(obj, list):
return [todict(a) for a in obj]
return [todict(a, post_processor) for a in obj]
elif isinstance(obj, Enum):
return obj.value
elif isinstance(obj, (date, time, datetime)):
return obj.isoformat()
elif isinstance(obj, timedelta):
return str(obj)
elif hasattr(obj, '_asdict'):
return todict(obj._asdict())
return todict(obj._asdict(), post_processor)
elif hasattr(obj, '__dict__'):
return dict([(to_camel_case(k), todict(v))
for k, v in obj.__dict__.items()
if not callable(v) and not k.startswith('_')])
result = dict([(to_camel_case(k), todict(v, post_processor))
for k, v in obj.__dict__.items()
if not callable(v) and not k.startswith('_')])
return post_processor(obj, result) if post_processor else result
return obj
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from codecs import open
from setuptools import setup, find_packages

VERSION = '0.3.2'
VERSION = '0.3.3'

DEPENDENCIES = [
'argcomplete',
Expand Down