More generic todict

pull/2403/head
Hilton Bristow 11 years ago
parent 72d5609a36
commit 068b1bc3d0
  1. 33
      modules/matlab/generator/parse_tree.py

@ -1,3 +1,4 @@
import collections
from textwrap import fill from textwrap import fill
from filters import * from filters import *
@ -333,23 +334,31 @@ def constants(tree):
for gen in constants(val): for gen in constants(val):
yield gen yield gen
def isstring(s):
"""
Check if variable is string representable (regular/unicode/raw)
in a Python 2 and 3 compatible manner
"""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
def todict(obj, classkey=None): def todict(obj, classkey=None):
""" """
Convert the ParseTree to a dictionary, stripping all objects of their Convert the ParseTree to a dictionary, stripping all objects of their
methods and converting class names to strings methods and converting class names to strings
""" """
if isstring(obj):
return obj
if isinstance(obj, dict): if isinstance(obj, dict):
for k in obj.keys(): obj.update((key, todict(val, classkey)) for key, val in obj.items())
obj[k] = todict(obj[k], classkey)
return obj return obj
elif isinstance(obj, list): if isinstance(obj, collections.Iterable):
return [todict(v, classkey) for v in obj] return [todict(val, classkey) for val in obj]
elif hasattr(obj, "__dict__"): if hasattr(obj, '__dict__'):
data = dict([(key, todict(value, classkey)) attrs = dict((key, todict(val, classkey)) for key, val in vars(obj).items())
for key, value in obj.__dict__.items() if classkey is not None and hasattr(obj, '__class__'):
if not callable(value) and not key.startswith('_')])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__ data[classkey] = obj.__class__.__name__
return data return attrs
else: return obj
return obj

Loading…
Cancel
Save