|
| 1 | +from __future__ import print_function |
| 2 | + |
| 3 | +import collections |
| 4 | + |
| 5 | +import six |
| 6 | + |
| 7 | + |
| 8 | +def objwalk(obj, path=(), memo=None): |
| 9 | + # Based on https://gist.github.com/sente/1480558 |
| 10 | + if memo is None: |
| 11 | + memo = set() |
| 12 | + if id(obj) not in memo: |
| 13 | + memo.add(id(obj)) |
| 14 | + if isinstance(obj, collections.Mapping): |
| 15 | + for key, value in six.iteritems(obj): |
| 16 | + for child in objwalk(value, path + (key,), memo): |
| 17 | + yield child |
| 18 | + elif (isinstance(obj, (collections.Sequence, collections.Set)) and |
| 19 | + not isinstance(obj, six.string_types)): |
| 20 | + for index, value in enumerate(obj): |
| 21 | + for child in objwalk(value, path + (index,), memo): |
| 22 | + yield child |
| 23 | + else: |
| 24 | + yield path, obj |
| 25 | + if hasattr(obj, '__dict__'): |
| 26 | + for child in objwalk(obj.__dict__, path + ('__dict__',), memo): |
| 27 | + yield child |
| 28 | + |
| 29 | + |
| 30 | +class Version(object): |
| 31 | + |
| 32 | + def __init__(self): |
| 33 | + self.major = 1 |
| 34 | + self.minor = 2 |
| 35 | + |
| 36 | + |
| 37 | +class Info(object): |
| 38 | + |
| 39 | + def __init__(self): |
| 40 | + self.lst = [Version(), Version()] |
| 41 | + self.dct = {'a': Version()} |
| 42 | + self.version = Version() |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == '__main__': |
| 46 | + for path, obj in objwalk(Info()): |
| 47 | + print(path, repr(obj)) |
0 commit comments