pyclbr.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. """Parse a Python module and describe its classes and methods.
  2. Parse enough of a Python file to recognize imports and class and
  3. method definitions, and to find out the superclasses of a class.
  4. The interface consists of a single function:
  5. readmodule_ex(module [, path])
  6. where module is the name of a Python module, and path is an optional
  7. list of directories where the module is to be searched. If present,
  8. path is prepended to the system search path sys.path. The return
  9. value is a dictionary. The keys of the dictionary are the names of
  10. the classes defined in the module (including classes that are defined
  11. via the from XXX import YYY construct). The values are class
  12. instances of the class Class defined here. One special key/value pair
  13. is present for packages: the key '__path__' has a list as its value
  14. which contains the package search path.
  15. A class is described by the class Class in this module. Instances
  16. of this class have the following instance variables:
  17. module -- the module name
  18. name -- the name of the class
  19. super -- a list of super classes (Class instances)
  20. methods -- a dictionary of methods
  21. file -- the file in which the class was defined
  22. lineno -- the line in the file on which the class statement occurred
  23. The dictionary of methods uses the method names as keys and the line
  24. numbers on which the method was defined as values.
  25. If the name of a super class is not recognized, the corresponding
  26. entry in the list of super classes is not a class instance but a
  27. string giving the name of the super class. Since import statements
  28. are recognized and imported modules are scanned as well, this
  29. shouldn't happen often.
  30. A function is described by the class Function in this module.
  31. Instances of this class have the following instance variables:
  32. module -- the module name
  33. name -- the name of the class
  34. file -- the file in which the class was defined
  35. lineno -- the line in the file on which the class statement occurred
  36. """
  37. import sys
  38. import imp
  39. import tokenize # Python tokenizer
  40. from token import NAME, DEDENT, NEWLINE
  41. from operator import itemgetter
  42. __all__ = ["readmodule", "readmodule_ex", "Class", "Function"]
  43. _modules = {} # cache of modules we've seen
  44. # each Python class is represented by an instance of this class
  45. class Class:
  46. '''Class to represent a Python class.'''
  47. def __init__(self, module, name, super, file, lineno):
  48. self.module = module
  49. self.name = name
  50. if super is None:
  51. super = []
  52. self.super = super
  53. self.methods = {}
  54. self.file = file
  55. self.lineno = lineno
  56. def _addmethod(self, name, lineno):
  57. self.methods[name] = lineno
  58. class Function:
  59. '''Class to represent a top-level Python function'''
  60. def __init__(self, module, name, file, lineno):
  61. self.module = module
  62. self.name = name
  63. self.file = file
  64. self.lineno = lineno
  65. def readmodule(module, path=[]):
  66. '''Backwards compatible interface.
  67. Call readmodule_ex() and then only keep Class objects from the
  68. resulting dictionary.'''
  69. dict = _readmodule(module, path)
  70. res = {}
  71. for key, value in dict.items():
  72. if isinstance(value, Class):
  73. res[key] = value
  74. return res
  75. def readmodule_ex(module, path=[]):
  76. '''Read a module file and return a dictionary of classes.
  77. Search for MODULE in PATH and sys.path, read and parse the
  78. module and return a dictionary with one entry for each class
  79. found in the module.
  80. If INPACKAGE is true, it must be the dotted name of the package in
  81. which we are searching for a submodule, and then PATH must be the
  82. package search path; otherwise, we are searching for a top-level
  83. module, and PATH is combined with sys.path.
  84. '''
  85. return _readmodule(module, path)
  86. def _readmodule(module, path, inpackage=None):
  87. '''Do the hard work for readmodule[_ex].'''
  88. # Compute the full module name (prepending inpackage if set)
  89. if inpackage:
  90. fullmodule = "%s.%s" % (inpackage, module)
  91. else:
  92. fullmodule = module
  93. # Check in the cache
  94. if fullmodule in _modules:
  95. return _modules[fullmodule]
  96. # Initialize the dict for this module's contents
  97. dict = {}
  98. # Check if it is a built-in module; we don't do much for these
  99. if module in sys.builtin_module_names and not inpackage:
  100. _modules[module] = dict
  101. return dict
  102. # Check for a dotted module name
  103. i = module.rfind('.')
  104. if i >= 0:
  105. package = module[:i]
  106. submodule = module[i+1:]
  107. parent = _readmodule(package, path, inpackage)
  108. if inpackage:
  109. package = "%s.%s" % (inpackage, package)
  110. return _readmodule(submodule, parent['__path__'], package)
  111. # Search the path for the module
  112. f = None
  113. if inpackage:
  114. f, file, (suff, mode, type) = imp.find_module(module, path)
  115. else:
  116. f, file, (suff, mode, type) = imp.find_module(module, path + sys.path)
  117. if type == imp.PKG_DIRECTORY:
  118. dict['__path__'] = [file]
  119. path = [file] + path
  120. f, file, (suff, mode, type) = imp.find_module('__init__', [file])
  121. _modules[fullmodule] = dict
  122. if type != imp.PY_SOURCE:
  123. # not Python source, can't do anything with this module
  124. f.close()
  125. return dict
  126. stack = [] # stack of (class, indent) pairs
  127. g = tokenize.generate_tokens(f.readline)
  128. try:
  129. for tokentype, token, start, end, line in g:
  130. if tokentype == DEDENT:
  131. lineno, thisindent = start
  132. # close nested classes and defs
  133. while stack and stack[-1][1] >= thisindent:
  134. del stack[-1]
  135. elif token == 'def':
  136. lineno, thisindent = start
  137. # close previous nested classes and defs
  138. while stack and stack[-1][1] >= thisindent:
  139. del stack[-1]
  140. tokentype, meth_name, start, end, line = g.next()
  141. if tokentype != NAME:
  142. continue # Syntax error
  143. if stack:
  144. cur_class = stack[-1][0]
  145. if isinstance(cur_class, Class):
  146. # it's a method
  147. cur_class._addmethod(meth_name, lineno)
  148. # else it's a nested def
  149. else:
  150. # it's a function
  151. dict[meth_name] = Function(fullmodule, meth_name, file, lineno)
  152. stack.append((None, thisindent)) # Marker for nested fns
  153. elif token == 'class':
  154. lineno, thisindent = start
  155. # close previous nested classes and defs
  156. while stack and stack[-1][1] >= thisindent:
  157. del stack[-1]
  158. tokentype, class_name, start, end, line = g.next()
  159. if tokentype != NAME:
  160. continue # Syntax error
  161. # parse what follows the class name
  162. tokentype, token, start, end, line = g.next()
  163. inherit = None
  164. if token == '(':
  165. names = [] # List of superclasses
  166. # there's a list of superclasses
  167. level = 1
  168. super = [] # Tokens making up current superclass
  169. while True:
  170. tokentype, token, start, end, line = g.next()
  171. if token in (')', ',') and level == 1:
  172. n = "".join(super)
  173. if n in dict:
  174. # we know this super class
  175. n = dict[n]
  176. else:
  177. c = n.split('.')
  178. if len(c) > 1:
  179. # super class is of the form
  180. # module.class: look in module for
  181. # class
  182. m = c[-2]
  183. c = c[-1]
  184. if m in _modules:
  185. d = _modules[m]
  186. if c in d:
  187. n = d[c]
  188. names.append(n)
  189. super = []
  190. if token == '(':
  191. level += 1
  192. elif token == ')':
  193. level -= 1
  194. if level == 0:
  195. break
  196. elif token == ',' and level == 1:
  197. pass
  198. else:
  199. super.append(token)
  200. inherit = names
  201. cur_class = Class(fullmodule, class_name, inherit, file, lineno)
  202. if not stack:
  203. dict[class_name] = cur_class
  204. stack.append((cur_class, thisindent))
  205. elif token == 'import' and start[1] == 0:
  206. modules = _getnamelist(g)
  207. for mod, mod2 in modules:
  208. try:
  209. # Recursively read the imported module
  210. if not inpackage:
  211. _readmodule(mod, path)
  212. else:
  213. try:
  214. _readmodule(mod, path, inpackage)
  215. except ImportError:
  216. _readmodule(mod, [])
  217. except:
  218. # If we can't find or parse the imported module,
  219. # too bad -- don't die here.
  220. pass
  221. elif token == 'from' and start[1] == 0:
  222. mod, token = _getname(g)
  223. if not mod or token != "import":
  224. continue
  225. names = _getnamelist(g)
  226. try:
  227. # Recursively read the imported module
  228. d = _readmodule(mod, path, inpackage)
  229. except:
  230. # If we can't find or parse the imported module,
  231. # too bad -- don't die here.
  232. continue
  233. # add any classes that were defined in the imported module
  234. # to our name space if they were mentioned in the list
  235. for n, n2 in names:
  236. if n in d:
  237. dict[n2 or n] = d[n]
  238. elif n == '*':
  239. # don't add names that start with _
  240. for n in d:
  241. if n[0] != '_':
  242. dict[n] = d[n]
  243. except StopIteration:
  244. pass
  245. f.close()
  246. return dict
  247. def _getnamelist(g):
  248. # Helper to get a comma-separated list of dotted names plus 'as'
  249. # clauses. Return a list of pairs (name, name2) where name2 is
  250. # the 'as' name, or None if there is no 'as' clause.
  251. names = []
  252. while True:
  253. name, token = _getname(g)
  254. if not name:
  255. break
  256. if token == 'as':
  257. name2, token = _getname(g)
  258. else:
  259. name2 = None
  260. names.append((name, name2))
  261. while token != "," and "\n" not in token:
  262. tokentype, token, start, end, line = g.next()
  263. if token != ",":
  264. break
  265. return names
  266. def _getname(g):
  267. # Helper to get a dotted name, return a pair (name, token) where
  268. # name is the dotted name, or None if there was no dotted name,
  269. # and token is the next input token.
  270. parts = []
  271. tokentype, token, start, end, line = g.next()
  272. if tokentype != NAME and token != '*':
  273. return (None, token)
  274. parts.append(token)
  275. while True:
  276. tokentype, token, start, end, line = g.next()
  277. if token != '.':
  278. break
  279. tokentype, token, start, end, line = g.next()
  280. if tokentype != NAME:
  281. break
  282. parts.append(token)
  283. return (".".join(parts), token)
  284. def _main():
  285. # Main program for testing.
  286. import os
  287. mod = sys.argv[1]
  288. if os.path.exists(mod):
  289. path = [os.path.dirname(mod)]
  290. mod = os.path.basename(mod)
  291. if mod.lower().endswith(".py"):
  292. mod = mod[:-3]
  293. else:
  294. path = []
  295. dict = readmodule_ex(mod, path)
  296. objs = dict.values()
  297. objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0),
  298. getattr(b, 'lineno', 0)))
  299. for obj in objs:
  300. if isinstance(obj, Class):
  301. print "class", obj.name, obj.super, obj.lineno
  302. methods = sorted(obj.methods.iteritems(), key=itemgetter(1))
  303. for name, lineno in methods:
  304. if name != "__path__":
  305. print " def", name, lineno
  306. elif isinstance(obj, Function):
  307. print "def", obj.name, obj.lineno
  308. if __name__ == "__main__":
  309. _main()