Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. import inspect
  2. import networkx as nx
  3. import re
  4.  
  5.  
  6. __all__ = ['make_inheritance_tree']
  7.  
  8.  
  9. def get_classes(p, visited=None):
  10. """generator that yields all classes in a module or package"""
  11. if visited is None:
  12. visited = [id(p)]
  13.  
  14. for k, v in p.__dict__.items():
  15. if id(v) in visited:
  16. continue
  17. else:
  18. visited.append(id(v))
  19.  
  20. if inspect.ismodule(v):
  21. for item in get_classes(v, visited=visited):
  22. yield item
  23. elif isinstance(v, type):
  24. yield v
  25.  
  26.  
  27. def clsname(cls):
  28. """return the qualname of a class"""
  29. return cls.__module__+'.'+cls.__name__
  30.  
  31.  
  32. def graph_class(G, cls, root=None, visited=None):
  33. """
  34. make a graph for a single class by connecting the classes from the method resolution order
  35. classes not within the root name are not checked for mro
  36. """
  37. if visited is None:
  38. visited = [id(cls)]
  39.  
  40. for supercls in type.mro(cls):
  41. if id(supercls) in visited:
  42. continue
  43. else:
  44. visited.append(id(cls))
  45.  
  46. G.add_edge(clsname(supercls), clsname(cls))
  47.  
  48. if supercls.__module__ == '__builtin__':
  49. continue
  50. if root and not supercls.__module__.startswith(root+'.'):
  51. continue
  52.  
  53. graph_class(G, supercls, root=root, visited=visited)
  54.  
  55.  
  56. def make_package_class_tree(p, maxcount=0, root=None):
  57. """create a graph for a package"""
  58. G = nx.DiGraph()
  59. visited = []
  60. for i, cls in enumerate(get_classes(p)):
  61. if id(cls) in visited:
  62. continue
  63. else:
  64. visited.append(id(cls))
  65.  
  66. graph_class(G, cls, root=root or p.__name__, visited=visited)
  67.  
  68. if i+1 >= maxcount:
  69. break
  70.  
  71. nx.draw_networkx(G)
  72.  
  73.  
  74. def make_class_tree(cls, root=None):
  75. """create a graph for a class"""
  76. G = nx.DiGraph()
  77. graph_class(G, cls, root=root or cls.__module__)
  78. nx.draw_networkx(G)
  79.  
  80.  
  81. def make_inheritance_tree(obj, maxcount=0, root=None):
  82. """create a graph for an arbitrary object"""
  83. if inspect.ismodule(obj):
  84. return make_package_class_tree(obj, maxcount=maxcount, root=root)
  85. elif not isinstance(obj, type):
  86. obj = type(obj)
  87. return make_class_tree(obj, root=root)
  88.  
  89.  
  90. if __name__ == '__main__':
  91. from matplotlib import pyplot as plt
  92. make_inheritance_tree(plt.Axes, root='matplotlib')
  93.  
  94. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement