Skip to content

Commit

Permalink
expose a callback to let client side perform extra logics (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
yugangw-msft authored May 2, 2018
1 parent f475698 commit c5f9af5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
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

0 comments on commit c5f9af5

Please sign in to comment.