PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/pydoc.py

https://bitbucket.org/quangquach/pypy
Python | 2360 lines | 2300 code | 35 blank | 25 comment | 98 complexity | 385e5e211898c88c74373fd9e5740f03 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python
  2. # -*- coding: latin-1 -*-
  3. """Generate Python documentation in HTML or text for interactive use.
  4. In the Python interpreter, do "from pydoc import help" to provide online
  5. help. Calling help(thing) on a Python object documents the object.
  6. Or, at the shell command line outside of Python:
  7. Run "pydoc <name>" to show documentation on something. <name> may be
  8. the name of a function, module, package, or a dotted reference to a
  9. class or function within a module or module in a package. If the
  10. argument contains a path segment delimiter (e.g. slash on Unix,
  11. backslash on Windows) it is treated as the path to a Python source file.
  12. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  13. of all available modules.
  14. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  15. local machine to generate documentation web pages.
  16. For platforms without a command line, "pydoc -g" starts the HTTP server
  17. and also pops up a little window for controlling it.
  18. Run "pydoc -w <name>" to write out the HTML documentation for a module
  19. to a file named "<name>.html".
  20. Module docs for core modules are assumed to be in
  21. http://docs.python.org/library/
  22. This can be overridden by setting the PYTHONDOCS environment variable
  23. to a different URL or to a local directory containing the Library
  24. Reference Manual pages.
  25. """
  26. __author__ = "Ka-Ping Yee <ping@lfw.org>"
  27. __date__ = "26 February 2001"
  28. __version__ = "$Revision: 88564 $"
  29. __credits__ = """Guido van Rossum, for an excellent programming language.
  30. Tommy Burnette, the original creator of manpy.
  31. Paul Prescod, for all his work on onlinehelp.
  32. Richard Chamberlain, for the first implementation of textdoc.
  33. """
  34. # Known bugs that can't be fixed here:
  35. # - imp.load_module() cannot be prevented from clobbering existing
  36. # loaded modules, so calling synopsis() on a binary module file
  37. # changes the contents of any existing module with the same name.
  38. # - If the __file__ attribute on a module is a relative path and
  39. # the current directory is changed with os.chdir(), an incorrect
  40. # path will be displayed.
  41. import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings
  42. from repr import Repr
  43. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  44. from traceback import extract_tb
  45. try:
  46. from collections import deque
  47. except ImportError:
  48. # Python 2.3 compatibility
  49. class deque(list):
  50. def popleft(self):
  51. return self.pop(0)
  52. # --------------------------------------------------------- common routines
  53. def pathdirs():
  54. """Convert sys.path into a list of absolute, existing, unique paths."""
  55. dirs = []
  56. normdirs = []
  57. for dir in sys.path:
  58. dir = os.path.abspath(dir or '.')
  59. normdir = os.path.normcase(dir)
  60. if normdir not in normdirs and os.path.isdir(dir):
  61. dirs.append(dir)
  62. normdirs.append(normdir)
  63. return dirs
  64. def getdoc(object):
  65. """Get the doc string or comments for an object."""
  66. result = inspect.getdoc(object) or inspect.getcomments(object)
  67. return result and re.sub('^ *\n', '', rstrip(result)) or ''
  68. def splitdoc(doc):
  69. """Split a doc string into a synopsis line (if any) and the rest."""
  70. lines = split(strip(doc), '\n')
  71. if len(lines) == 1:
  72. return lines[0], ''
  73. elif len(lines) >= 2 and not rstrip(lines[1]):
  74. return lines[0], join(lines[2:], '\n')
  75. return '', join(lines, '\n')
  76. def classname(object, modname):
  77. """Get a class name and qualify it with a module name if necessary."""
  78. name = object.__name__
  79. if object.__module__ != modname:
  80. name = object.__module__ + '.' + name
  81. return name
  82. def isdata(object):
  83. """Check if an object is of a type that probably means it's data."""
  84. return not (inspect.ismodule(object) or inspect.isclass(object) or
  85. inspect.isroutine(object) or inspect.isframe(object) or
  86. inspect.istraceback(object) or inspect.iscode(object))
  87. def replace(text, *pairs):
  88. """Do a series of global replacements on a string."""
  89. while pairs:
  90. text = join(split(text, pairs[0]), pairs[1])
  91. pairs = pairs[2:]
  92. return text
  93. def cram(text, maxlen):
  94. """Omit part of a string if needed to make it fit in a maximum length."""
  95. if len(text) > maxlen:
  96. pre = max(0, (maxlen-3)//2)
  97. post = max(0, maxlen-3-pre)
  98. return text[:pre] + '...' + text[len(text)-post:]
  99. return text
  100. _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  101. def stripid(text):
  102. """Remove the hexadecimal id from a Python object representation."""
  103. # The behaviour of %p is implementation-dependent in terms of case.
  104. return _re_stripid.sub(r'\1', text)
  105. def _is_some_method(obj):
  106. return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
  107. def allmethods(cl):
  108. methods = {}
  109. for key, value in inspect.getmembers(cl, _is_some_method):
  110. methods[key] = 1
  111. for base in cl.__bases__:
  112. methods.update(allmethods(base)) # all your base are belong to us
  113. for key in methods.keys():
  114. methods[key] = getattr(cl, key)
  115. return methods
  116. def _split_list(s, predicate):
  117. """Split sequence s via predicate, and return pair ([true], [false]).
  118. The return value is a 2-tuple of lists,
  119. ([x for x in s if predicate(x)],
  120. [x for x in s if not predicate(x)])
  121. """
  122. yes = []
  123. no = []
  124. for x in s:
  125. if predicate(x):
  126. yes.append(x)
  127. else:
  128. no.append(x)
  129. return yes, no
  130. def visiblename(name, all=None, obj=None):
  131. """Decide whether to show documentation on a variable."""
  132. # Certain special names are redundant.
  133. _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__',
  134. '__module__', '__name__', '__slots__', '__package__')
  135. if name in _hidden_names: return 0
  136. # Private names are hidden, but special names are displayed.
  137. if name.startswith('__') and name.endswith('__'): return 1
  138. # Namedtuples have public fields and methods with a single leading underscore
  139. if name.startswith('_') and hasattr(obj, '_fields'):
  140. return 1
  141. if all is not None:
  142. # only document that which the programmer exported in __all__
  143. return name in all
  144. else:
  145. return not name.startswith('_')
  146. def classify_class_attrs(object):
  147. """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
  148. def fixup(data):
  149. name, kind, cls, value = data
  150. if inspect.isdatadescriptor(value):
  151. kind = 'data descriptor'
  152. return name, kind, cls, value
  153. return map(fixup, inspect.classify_class_attrs(object))
  154. # ----------------------------------------------------- module manipulation
  155. def ispackage(path):
  156. """Guess whether a path refers to a package directory."""
  157. if os.path.isdir(path):
  158. for ext in ('.py', '.pyc', '.pyo'):
  159. if os.path.isfile(os.path.join(path, '__init__' + ext)):
  160. return True
  161. return False
  162. def source_synopsis(file):
  163. line = file.readline()
  164. while line[:1] == '#' or not strip(line):
  165. line = file.readline()
  166. if not line: break
  167. line = strip(line)
  168. if line[:4] == 'r"""': line = line[1:]
  169. if line[:3] == '"""':
  170. line = line[3:]
  171. if line[-1:] == '\\': line = line[:-1]
  172. while not strip(line):
  173. line = file.readline()
  174. if not line: break
  175. result = strip(split(line, '"""')[0])
  176. else: result = None
  177. return result
  178. def synopsis(filename, cache={}):
  179. """Get the one-line summary out of a module file."""
  180. mtime = os.stat(filename).st_mtime
  181. lastupdate, result = cache.get(filename, (None, None))
  182. if lastupdate is None or lastupdate < mtime:
  183. info = inspect.getmoduleinfo(filename)
  184. try:
  185. file = open(filename)
  186. except IOError:
  187. # module can't be opened, so skip it
  188. return None
  189. if info and 'b' in info[2]: # binary modules have to be imported
  190. try: module = imp.load_module('__temp__', file, filename, info[1:])
  191. except: return None
  192. result = (module.__doc__ or '').splitlines()[0]
  193. del sys.modules['__temp__']
  194. else: # text modules can be directly examined
  195. result = source_synopsis(file)
  196. file.close()
  197. cache[filename] = (mtime, result)
  198. return result
  199. class ErrorDuringImport(Exception):
  200. """Errors that occurred while trying to import something to document it."""
  201. def __init__(self, filename, exc_info):
  202. exc, value, tb = exc_info
  203. self.filename = filename
  204. self.exc = exc
  205. self.value = value
  206. self.tb = tb
  207. def __str__(self):
  208. exc = self.exc
  209. if type(exc) is types.ClassType:
  210. exc = exc.__name__
  211. return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  212. def importfile(path):
  213. """Import a Python source file or compiled file given its path."""
  214. magic = imp.get_magic()
  215. file = open(path, 'r')
  216. if file.read(len(magic)) == magic:
  217. kind = imp.PY_COMPILED
  218. else:
  219. kind = imp.PY_SOURCE
  220. file.close()
  221. filename = os.path.basename(path)
  222. name, ext = os.path.splitext(filename)
  223. file = open(path, 'r')
  224. try:
  225. module = imp.load_module(name, file, path, (ext, 'r', kind))
  226. except:
  227. raise ErrorDuringImport(path, sys.exc_info())
  228. file.close()
  229. return module
  230. def safeimport(path, forceload=0, cache={}):
  231. """Import a module; handle errors; return None if the module isn't found.
  232. If the module *is* found but an exception occurs, it's wrapped in an
  233. ErrorDuringImport exception and reraised. Unlike __import__, if a
  234. package path is specified, the module at the end of the path is returned,
  235. not the package at the beginning. If the optional 'forceload' argument
  236. is 1, we reload the module from disk (unless it's a dynamic extension)."""
  237. try:
  238. # If forceload is 1 and the module has been previously loaded from
  239. # disk, we always have to reload the module. Checking the file's
  240. # mtime isn't good enough (e.g. the module could contain a class
  241. # that inherits from another module that has changed).
  242. if forceload and path in sys.modules:
  243. if path not in sys.builtin_module_names:
  244. # Avoid simply calling reload() because it leaves names in
  245. # the currently loaded module lying around if they're not
  246. # defined in the new source file. Instead, remove the
  247. # module from sys.modules and re-import. Also remove any
  248. # submodules because they won't appear in the newly loaded
  249. # module's namespace if they're already in sys.modules.
  250. subs = [m for m in sys.modules if m.startswith(path + '.')]
  251. for key in [path] + subs:
  252. # Prevent garbage collection.
  253. cache[key] = sys.modules[key]
  254. del sys.modules[key]
  255. module = __import__(path)
  256. except:
  257. # Did the error occur before or after the module was found?
  258. (exc, value, tb) = info = sys.exc_info()
  259. if path in sys.modules:
  260. # An error occurred while executing the imported module.
  261. raise ErrorDuringImport(sys.modules[path].__file__, info)
  262. elif exc is SyntaxError:
  263. # A SyntaxError occurred before we could execute the module.
  264. raise ErrorDuringImport(value.filename, info)
  265. elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport':
  266. # The import error occurred directly in this function,
  267. # which means there is no such module in the path.
  268. return None
  269. else:
  270. # Some other error occurred during the importing process.
  271. raise ErrorDuringImport(path, sys.exc_info())
  272. for part in split(path, '.')[1:]:
  273. try: module = getattr(module, part)
  274. except AttributeError: return None
  275. return module
  276. # ---------------------------------------------------- formatter base class
  277. class Doc:
  278. def document(self, object, name=None, *args):
  279. """Generate documentation for an object."""
  280. args = (object, name) + args
  281. # 'try' clause is to attempt to handle the possibility that inspect
  282. # identifies something in a way that pydoc itself has issues handling;
  283. # think 'super' and how it is a descriptor (which raises the exception
  284. # by lacking a __name__ attribute) and an instance.
  285. if inspect.isgetsetdescriptor(object): return self.docdata(*args)
  286. if inspect.ismemberdescriptor(object): return self.docdata(*args)
  287. try:
  288. if inspect.ismodule(object): return self.docmodule(*args)
  289. if inspect.isclass(object): return self.docclass(*args)
  290. if inspect.isroutine(object): return self.docroutine(*args)
  291. except AttributeError:
  292. pass
  293. if isinstance(object, property): return self.docproperty(*args)
  294. return self.docother(*args)
  295. def fail(self, object, name=None, *args):
  296. """Raise an exception for unimplemented types."""
  297. message = "don't know how to document object%s of type %s" % (
  298. name and ' ' + repr(name), type(object).__name__)
  299. raise TypeError, message
  300. docmodule = docclass = docroutine = docother = docproperty = docdata = fail
  301. def getdocloc(self, object):
  302. """Return the location of module docs or None"""
  303. try:
  304. file = inspect.getabsfile(object)
  305. except TypeError:
  306. file = '(built-in)'
  307. docloc = os.environ.get("PYTHONDOCS",
  308. "http://docs.python.org/library")
  309. basedir = os.path.join(sys.exec_prefix, "lib",
  310. "python"+sys.version[0:3])
  311. if (isinstance(object, type(os)) and
  312. (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
  313. 'marshal', 'posix', 'signal', 'sys',
  314. 'thread', 'zipimport') or
  315. (file.startswith(basedir) and
  316. not file.startswith(os.path.join(basedir, 'site-packages')))) and
  317. object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
  318. if docloc.startswith("http://"):
  319. docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
  320. else:
  321. docloc = os.path.join(docloc, object.__name__ + ".html")
  322. else:
  323. docloc = None
  324. return docloc
  325. # -------------------------------------------- HTML documentation generator
  326. class HTMLRepr(Repr):
  327. """Class for safely making an HTML representation of a Python object."""
  328. def __init__(self):
  329. Repr.__init__(self)
  330. self.maxlist = self.maxtuple = 20
  331. self.maxdict = 10
  332. self.maxstring = self.maxother = 100
  333. def escape(self, text):
  334. return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
  335. def repr(self, object):
  336. return Repr.repr(self, object)
  337. def repr1(self, x, level):
  338. if hasattr(type(x), '__name__'):
  339. methodname = 'repr_' + join(split(type(x).__name__), '_')
  340. if hasattr(self, methodname):
  341. return getattr(self, methodname)(x, level)
  342. return self.escape(cram(stripid(repr(x)), self.maxother))
  343. def repr_string(self, x, level):
  344. test = cram(x, self.maxstring)
  345. testrepr = repr(test)
  346. if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  347. # Backslashes are only literal in the string and are never
  348. # needed to make any special characters, so show a raw string.
  349. return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  350. return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
  351. r'<font color="#c040c0">\1</font>',
  352. self.escape(testrepr))
  353. repr_str = repr_string
  354. def repr_instance(self, x, level):
  355. try:
  356. return self.escape(cram(stripid(repr(x)), self.maxstring))
  357. except:
  358. return self.escape('<%s instance>' % x.__class__.__name__)
  359. repr_unicode = repr_string
  360. class HTMLDoc(Doc):
  361. """Formatter class for HTML documentation."""
  362. # ------------------------------------------- HTML formatting utilities
  363. _repr_instance = HTMLRepr()
  364. repr = _repr_instance.repr
  365. escape = _repr_instance.escape
  366. def page(self, title, contents):
  367. """Format an HTML page."""
  368. return '''
  369. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  370. <html><head><title>Python: %s</title>
  371. </head><body bgcolor="#f0f0f8">
  372. %s
  373. </body></html>''' % (title, contents)
  374. def heading(self, title, fgcol, bgcol, extras=''):
  375. """Format a page heading."""
  376. return '''
  377. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  378. <tr bgcolor="%s">
  379. <td valign=bottom>&nbsp;<br>
  380. <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
  381. ><td align=right valign=bottom
  382. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
  383. ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
  384. def section(self, title, fgcol, bgcol, contents, width=6,
  385. prelude='', marginalia=None, gap='&nbsp;'):
  386. """Format a section with a heading."""
  387. if marginalia is None:
  388. marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
  389. result = '''<p>
  390. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  391. <tr bgcolor="%s">
  392. <td colspan=3 valign=bottom>&nbsp;<br>
  393. <font color="%s" face="helvetica, arial">%s</font></td></tr>
  394. ''' % (bgcol, fgcol, title)
  395. if prelude:
  396. result = result + '''
  397. <tr bgcolor="%s"><td rowspan=2>%s</td>
  398. <td colspan=2>%s</td></tr>
  399. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
  400. else:
  401. result = result + '''
  402. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
  403. return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  404. def bigsection(self, title, *args):
  405. """Format a section with a big heading."""
  406. title = '<big><strong>%s</strong></big>' % title
  407. return self.section(title, *args)
  408. def preformat(self, text):
  409. """Format literal preformatted text."""
  410. text = self.escape(expandtabs(text))
  411. return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
  412. ' ', '&nbsp;', '\n', '<br>\n')
  413. def multicolumn(self, list, format, cols=4):
  414. """Format a list of items into a multi-column list."""
  415. result = ''
  416. rows = (len(list)+cols-1)//cols
  417. for col in range(cols):
  418. result = result + '<td width="%d%%" valign=top>' % (100//cols)
  419. for i in range(rows*col, rows*col+rows):
  420. if i < len(list):
  421. result = result + format(list[i]) + '<br>\n'
  422. result = result + '</td>'
  423. return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  424. def grey(self, text): return '<font color="#909090">%s</font>' % text
  425. def namelink(self, name, *dicts):
  426. """Make a link for an identifier, given name-to-URL mappings."""
  427. for dict in dicts:
  428. if name in dict:
  429. return '<a href="%s">%s</a>' % (dict[name], name)
  430. return name
  431. def classlink(self, object, modname):
  432. """Make a link for a class."""
  433. name, module = object.__name__, sys.modules.get(object.__module__)
  434. if hasattr(module, name) and getattr(module, name) is object:
  435. return '<a href="%s.html#%s">%s</a>' % (
  436. module.__name__, name, classname(object, modname))
  437. return classname(object, modname)
  438. def modulelink(self, object):
  439. """Make a link for a module."""
  440. return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  441. def modpkglink(self, data):
  442. """Make a link for a module or package to display in an index."""
  443. name, path, ispackage, shadowed = data
  444. if shadowed:
  445. return self.grey(name)
  446. if path:
  447. url = '%s.%s.html' % (path, name)
  448. else:
  449. url = '%s.html' % name
  450. if ispackage:
  451. text = '<strong>%s</strong>&nbsp;(package)' % name
  452. else:
  453. text = name
  454. return '<a href="%s">%s</a>' % (url, text)
  455. def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  456. """Mark up some plain text, given a context of symbols to look for.
  457. Each context dictionary maps object names to anchor names."""
  458. escape = escape or self.escape
  459. results = []
  460. here = 0
  461. pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
  462. r'RFC[- ]?(\d+)|'
  463. r'PEP[- ]?(\d+)|'
  464. r'(self\.)?(\w+))')
  465. while True:
  466. match = pattern.search(text, here)
  467. if not match: break
  468. start, end = match.span()
  469. results.append(escape(text[here:start]))
  470. all, scheme, rfc, pep, selfdot, name = match.groups()
  471. if scheme:
  472. url = escape(all).replace('"', '&quot;')
  473. results.append('<a href="%s">%s</a>' % (url, url))
  474. elif rfc:
  475. url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  476. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  477. elif pep:
  478. url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
  479. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  480. elif text[end:end+1] == '(':
  481. results.append(self.namelink(name, methods, funcs, classes))
  482. elif selfdot:
  483. results.append('self.<strong>%s</strong>' % name)
  484. else:
  485. results.append(self.namelink(name, classes))
  486. here = end
  487. results.append(escape(text[here:]))
  488. return join(results, '')
  489. # ---------------------------------------------- type-specific routines
  490. def formattree(self, tree, modname, parent=None):
  491. """Produce HTML for a class tree as given by inspect.getclasstree()."""
  492. result = ''
  493. for entry in tree:
  494. if type(entry) is type(()):
  495. c, bases = entry
  496. result = result + '<dt><font face="helvetica, arial">'
  497. result = result + self.classlink(c, modname)
  498. if bases and bases != (parent,):
  499. parents = []
  500. for base in bases:
  501. parents.append(self.classlink(base, modname))
  502. result = result + '(' + join(parents, ', ') + ')'
  503. result = result + '\n</font></dt>'
  504. elif type(entry) is type([]):
  505. result = result + '<dd>\n%s</dd>\n' % self.formattree(
  506. entry, modname, c)
  507. return '<dl>\n%s</dl>\n' % result
  508. def docmodule(self, object, name=None, mod=None, *ignored):
  509. """Produce HTML documentation for a module object."""
  510. name = object.__name__ # ignore the passed-in name
  511. try:
  512. all = object.__all__
  513. except AttributeError:
  514. all = None
  515. parts = split(name, '.')
  516. links = []
  517. for i in range(len(parts)-1):
  518. links.append(
  519. '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
  520. (join(parts[:i+1], '.'), parts[i]))
  521. linkedname = join(links + parts[-1:], '.')
  522. head = '<big><big><strong>%s</strong></big></big>' % linkedname
  523. try:
  524. path = inspect.getabsfile(object)
  525. url = path
  526. if sys.platform == 'win32':
  527. import nturl2path
  528. url = nturl2path.pathname2url(path)
  529. filelink = '<a href="file:%s">%s</a>' % (url, path)
  530. except TypeError:
  531. filelink = '(built-in)'
  532. info = []
  533. if hasattr(object, '__version__'):
  534. version = str(object.__version__)
  535. if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  536. version = strip(version[11:-1])
  537. info.append('version %s' % self.escape(version))
  538. if hasattr(object, '__date__'):
  539. info.append(self.escape(str(object.__date__)))
  540. if info:
  541. head = head + ' (%s)' % join(info, ', ')
  542. docloc = self.getdocloc(object)
  543. if docloc is not None:
  544. docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
  545. else:
  546. docloc = ''
  547. result = self.heading(
  548. head, '#ffffff', '#7799ee',
  549. '<a href=".">index</a><br>' + filelink + docloc)
  550. def isnonbuiltinmodule(obj):
  551. return inspect.ismodule(obj) and obj is not __builtin__
  552. modules = inspect.getmembers(object, isnonbuiltinmodule)
  553. classes, cdict = [], {}
  554. for key, value in inspect.getmembers(object, inspect.isclass):
  555. # if __all__ exists, believe it. Otherwise use old heuristic.
  556. if (all is not None or
  557. (inspect.getmodule(value) or object) is object):
  558. if visiblename(key, all, object):
  559. classes.append((key, value))
  560. cdict[key] = cdict[value] = '#' + key
  561. for key, value in classes:
  562. for base in value.__bases__:
  563. key, modname = base.__name__, base.__module__
  564. module = sys.modules.get(modname)
  565. if modname != name and module and hasattr(module, key):
  566. if getattr(module, key) is base:
  567. if not key in cdict:
  568. cdict[key] = cdict[base] = modname + '.html#' + key
  569. funcs, fdict = [], {}
  570. for key, value in inspect.getmembers(object, inspect.isroutine):
  571. # if __all__ exists, believe it. Otherwise use old heuristic.
  572. if (all is not None or
  573. inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  574. if visiblename(key, all, object):
  575. funcs.append((key, value))
  576. fdict[key] = '#-' + key
  577. if inspect.isfunction(value): fdict[value] = fdict[key]
  578. data = []
  579. for key, value in inspect.getmembers(object, isdata):
  580. if visiblename(key, all, object):
  581. data.append((key, value))
  582. doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  583. doc = doc and '<tt>%s</tt>' % doc
  584. result = result + '<p>%s</p>\n' % doc
  585. if hasattr(object, '__path__'):
  586. modpkgs = []
  587. for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  588. modpkgs.append((modname, name, ispkg, 0))
  589. modpkgs.sort()
  590. contents = self.multicolumn(modpkgs, self.modpkglink)
  591. result = result + self.bigsection(
  592. 'Package Contents', '#ffffff', '#aa55cc', contents)
  593. elif modules:
  594. contents = self.multicolumn(
  595. modules, lambda key_value, s=self: s.modulelink(key_value[1]))
  596. result = result + self.bigsection(
  597. 'Modules', '#ffffff', '#aa55cc', contents)
  598. if classes:
  599. classlist = map(lambda key_value: key_value[1], classes)
  600. contents = [
  601. self.formattree(inspect.getclasstree(classlist, 1), name)]
  602. for key, value in classes:
  603. contents.append(self.document(value, key, name, fdict, cdict))
  604. result = result + self.bigsection(
  605. 'Classes', '#ffffff', '#ee77aa', join(contents))
  606. if funcs:
  607. contents = []
  608. for key, value in funcs:
  609. contents.append(self.document(value, key, name, fdict, cdict))
  610. result = result + self.bigsection(
  611. 'Functions', '#ffffff', '#eeaa77', join(contents))
  612. if data:
  613. contents = []
  614. for key, value in data:
  615. contents.append(self.document(value, key))
  616. result = result + self.bigsection(
  617. 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  618. if hasattr(object, '__author__'):
  619. contents = self.markup(str(object.__author__), self.preformat)
  620. result = result + self.bigsection(
  621. 'Author', '#ffffff', '#7799ee', contents)
  622. if hasattr(object, '__credits__'):
  623. contents = self.markup(str(object.__credits__), self.preformat)
  624. result = result + self.bigsection(
  625. 'Credits', '#ffffff', '#7799ee', contents)
  626. return result
  627. def docclass(self, object, name=None, mod=None, funcs={}, classes={},
  628. *ignored):
  629. """Produce HTML documentation for a class object."""
  630. realname = object.__name__
  631. name = name or realname
  632. bases = object.__bases__
  633. contents = []
  634. push = contents.append
  635. # Cute little class to pump out a horizontal rule between sections.
  636. class HorizontalRule:
  637. def __init__(self):
  638. self.needone = 0
  639. def maybe(self):
  640. if self.needone:
  641. push('<hr>\n')
  642. self.needone = 1
  643. hr = HorizontalRule()
  644. # List the mro, if non-trivial.
  645. mro = deque(inspect.getmro(object))
  646. if len(mro) > 2:
  647. hr.maybe()
  648. push('<dl><dt>Method resolution order:</dt>\n')
  649. for base in mro:
  650. push('<dd>%s</dd>\n' % self.classlink(base,
  651. object.__module__))
  652. push('</dl>\n')
  653. def spill(msg, attrs, predicate):
  654. ok, attrs = _split_list(attrs, predicate)
  655. if ok:
  656. hr.maybe()
  657. push(msg)
  658. for name, kind, homecls, value in ok:
  659. try:
  660. value = getattr(object, name)
  661. except Exception:
  662. # Some descriptors may meet a failure in their __get__.
  663. # (bug #1785)
  664. push(self._docdescriptor(name, value, mod))
  665. else:
  666. push(self.document(value, name, mod,
  667. funcs, classes, mdict, object))
  668. push('\n')
  669. return attrs
  670. def spilldescriptors(msg, attrs, predicate):
  671. ok, attrs = _split_list(attrs, predicate)
  672. if ok:
  673. hr.maybe()
  674. push(msg)
  675. for name, kind, homecls, value in ok:
  676. push(self._docdescriptor(name, value, mod))
  677. return attrs
  678. def spilldata(msg, attrs, predicate):
  679. ok, attrs = _split_list(attrs, predicate)
  680. if ok:
  681. hr.maybe()
  682. push(msg)
  683. for name, kind, homecls, value in ok:
  684. base = self.docother(getattr(object, name), name, mod)
  685. if (hasattr(value, '__call__') or
  686. inspect.isdatadescriptor(value)):
  687. doc = getattr(value, "__doc__", None)
  688. else:
  689. doc = None
  690. if doc is None:
  691. push('<dl><dt>%s</dl>\n' % base)
  692. else:
  693. doc = self.markup(getdoc(value), self.preformat,
  694. funcs, classes, mdict)
  695. doc = '<dd><tt>%s</tt>' % doc
  696. push('<dl><dt>%s%s</dl>\n' % (base, doc))
  697. push('\n')
  698. return attrs
  699. attrs = filter(lambda data: visiblename(data[0], obj=object),
  700. classify_class_attrs(object))
  701. mdict = {}
  702. for key, kind, homecls, value in attrs:
  703. mdict[key] = anchor = '#' + name + '-' + key
  704. try:
  705. value = getattr(object, name)
  706. except Exception:
  707. # Some descriptors may meet a failure in their __get__.
  708. # (bug #1785)
  709. pass
  710. try:
  711. # The value may not be hashable (e.g., a data attr with
  712. # a dict or list value).
  713. mdict[value] = anchor
  714. except TypeError:
  715. pass
  716. while attrs:
  717. if mro:
  718. thisclass = mro.popleft()
  719. else:
  720. thisclass = attrs[0][2]
  721. attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  722. if thisclass is __builtin__.object:
  723. attrs = inherited
  724. continue
  725. elif thisclass is object:
  726. tag = 'defined here'
  727. else:
  728. tag = 'inherited from %s' % self.classlink(thisclass,
  729. object.__module__)
  730. tag += ':<br>\n'
  731. # Sort attrs by name.
  732. try:
  733. attrs.sort(key=lambda t: t[0])
  734. except TypeError:
  735. attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat
  736. # Pump out the attrs, segregated by kind.
  737. attrs = spill('Methods %s' % tag, attrs,
  738. lambda t: t[1] == 'method')
  739. attrs = spill('Class methods %s' % tag, attrs,
  740. lambda t: t[1] == 'class method')
  741. attrs = spill('Static methods %s' % tag, attrs,
  742. lambda t: t[1] == 'static method')
  743. attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
  744. lambda t: t[1] == 'data descriptor')
  745. attrs = spilldata('Data and other attributes %s' % tag, attrs,
  746. lambda t: t[1] == 'data')
  747. assert attrs == []
  748. attrs = inherited
  749. contents = ''.join(contents)
  750. if name == realname:
  751. title = '<a name="%s">class <strong>%s</strong></a>' % (
  752. name, realname)
  753. else:
  754. title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
  755. name, name, realname)
  756. if bases:
  757. parents = []
  758. for base in bases:
  759. parents.append(self.classlink(base, object.__module__))
  760. title = title + '(%s)' % join(parents, ', ')
  761. doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  762. doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
  763. return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  764. def formatvalue(self, object):
  765. """Format an argument default value as text."""
  766. return self.grey('=' + self.repr(object))
  767. def docroutine(self, object, name=None, mod=None,
  768. funcs={}, classes={}, methods={}, cl=None):
  769. """Produce HTML documentation for a function or method object."""
  770. realname = object.__name__
  771. name = name or realname
  772. anchor = (cl and cl.__name__ or '') + '-' + name
  773. note = ''
  774. skipdocs = 0
  775. if inspect.ismethod(object):
  776. imclass = object.im_class
  777. if cl:
  778. if imclass is not cl:
  779. note = ' from ' + self.classlink(imclass, mod)
  780. else:
  781. if object.im_self is not None:
  782. note = ' method of %s instance' % self.classlink(
  783. object.im_self.__class__, mod)
  784. else:
  785. note = ' unbound %s method' % self.classlink(imclass,mod)
  786. object = object.im_func
  787. if name == realname:
  788. title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  789. else:
  790. if (cl and realname in cl.__dict__ and
  791. cl.__dict__[realname] is object):
  792. reallink = '<a href="#%s">%s</a>' % (
  793. cl.__name__ + '-' + realname, realname)
  794. skipdocs = 1
  795. else:
  796. reallink = realname
  797. title = '<a name="%s"><strong>%s</strong></a> = %s' % (
  798. anchor, name, reallink)
  799. if inspect.isfunction(object):
  800. args, varargs, varkw, defaults = inspect.getargspec(object)
  801. argspec = inspect.formatargspec(
  802. args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  803. if realname == '<lambda>':
  804. title = '<strong>%s</strong> <em>lambda</em> ' % name
  805. argspec = argspec[1:-1] # remove parentheses
  806. else:
  807. argspec = '(...)'
  808. decl = title + argspec + (note and self.grey(
  809. '<font face="helvetica, arial">%s</font>' % note))
  810. if skipdocs:
  811. return '<dl><dt>%s</dt></dl>\n' % decl
  812. else:
  813. doc = self.markup(
  814. getdoc(object), self.preformat, funcs, classes, methods)
  815. doc = doc and '<dd><tt>%s</tt></dd>' % doc
  816. return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  817. def _docdescriptor(self, name, value, mod):
  818. results = []
  819. push = results.append
  820. if name:
  821. push('<dl><dt><strong>%s</strong></dt>\n' % name)
  822. if value.__doc__ is not None:
  823. doc = self.markup(getdoc(value), self.preformat)
  824. push('<dd><tt>%s</tt></dd>\n' % doc)
  825. push('</dl>\n')
  826. return ''.join(results)
  827. def docproperty(self, object, name=None, mod=None, cl=None):
  828. """Produce html documentation for a property."""
  829. return self._docdescriptor(name, object, mod)
  830. def docother(self, object, name=None, mod=None, *ignored):
  831. """Produce HTML documentation for a data object."""
  832. lhs = name and '<strong>%s</strong> = ' % name or ''
  833. return lhs + self.repr(object)
  834. def docdata(self, object, name=None, mod=None, cl=None):
  835. """Produce html documentation for a data descriptor."""
  836. return self._docdescriptor(name, object, mod)
  837. def index(self, dir, shadowed=None):
  838. """Generate an HTML index for a directory of modules."""
  839. modpkgs = []
  840. if shadowed is None: shadowed = {}
  841. for importer, name, ispkg in pkgutil.iter_modules([dir]):
  842. modpkgs.append((name, '', ispkg, name in shadowed))
  843. shadowed[name] = 1
  844. modpkgs.sort()
  845. contents = self.multicolumn(modpkgs, self.modpkglink)
  846. return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  847. # -------------------------------------------- text documentation generator
  848. class TextRepr(Repr):
  849. """Class for safely making a text representation of a Python object."""
  850. def __init__(self):
  851. Repr.__init__(self)
  852. self.maxlist = self.maxtuple = 20
  853. self.maxdict = 10
  854. self.maxstring = self.maxother = 100
  855. def repr1(self, x, level):
  856. if hasattr(type(x), '__name__'):
  857. methodname = 'repr_' + join(split(type(x).__name__), '_')
  858. if hasattr(self, methodname):
  859. return getattr(self, methodname)(x, level)
  860. return cram(stripid(repr(x)), self.maxother)
  861. def repr_string(self, x, level):
  862. test = cram(x, self.maxstring)
  863. testrepr = repr(test)
  864. if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  865. # Backslashes are only literal in the string and are never
  866. # needed to make any special characters, so show a raw string.
  867. return 'r' + testrepr[0] + test + testrepr[0]
  868. return testrepr
  869. repr_str = repr_string
  870. def repr_instance(self, x, level):
  871. try:
  872. return cram(stripid(repr(x)), self.maxstring)
  873. except:
  874. return '<%s instance>' % x.__class__.__name__
  875. class TextDoc(Doc):
  876. """Formatter class for text documentation."""
  877. # ------------------------------------------- text formatting utilities
  878. _repr_instance = TextRepr()
  879. repr = _repr_instance.repr
  880. def bold(self, text):
  881. """Format a string in bold by overstriking."""
  882. return join(map(lambda ch: ch + '\b' + ch, text), '')
  883. def indent(self, text, prefix=' '):
  884. """Indent text by prepending a given prefix to each line."""
  885. if not text: return ''
  886. lines = split(text, '\n')
  887. lines = map(lambda line, prefix=prefix: prefix + line, lines)
  888. if lines: lines[-1] = rstrip(lines[-1])
  889. return join(lines, '\n')
  890. def section(self, title, contents):
  891. """Format a section with a given heading."""
  892. return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  893. # ---------------------------------------------- type-specific routines
  894. def formattree(self, tree, modname, parent=None, prefix=''):
  895. """Render in text a class tree as returned by inspect.getclasstree()."""
  896. result = ''
  897. for entry in tree:
  898. if type(entry) is type(()):
  899. c, bases = entry
  900. result = result + prefix + classname(c, modname)
  901. if bases and bases != (parent,):
  902. parents = map(lambda c, m=modname: classname(c, m), bases)
  903. result = result + '(%s)' % join(parents, ', ')
  904. result = result + '\n'
  905. elif type(entry) is type([]):
  906. result = result + self.formattree(
  907. entry, modname, c, prefix + ' ')
  908. return result
  909. def docmodule(self, object, name=None, mod=None):
  910. """Produce text documentation for a given module object."""
  911. name = object.__name__ # ignore the passed-in name
  912. synop, desc = splitdoc(getdoc(object))
  913. result = self.section('NAME', name + (synop and ' - ' + synop))
  914. try:
  915. all = object.__all__
  916. except AttributeError:
  917. all = None
  918. try:
  919. file = inspect.getabsfile(object)
  920. except TypeError:
  921. file = '(built-in)'
  922. result = result + self.section('FILE', file)
  923. docloc = self.getdocloc(object)
  924. if docloc is not None:
  925. result = result + self.section('MODULE DOCS', docloc)
  926. if desc:
  927. result = result + self.section('DESCRIPTION', desc)
  928. classes = []
  929. for key, value in inspect.getmembers(object, inspect.isclass):
  930. # if __all__ exists, believe it. Otherwise use old heuristic.
  931. if (all is not None
  932. or (inspect.getmodule(value) or object) is object):
  933. if visiblename(key, all, object):
  934. classes.append((key, value))
  935. funcs = []
  936. for key, value in inspect.getmembers(object, inspect.isroutine):
  937. # if __all__ exists, believe it. Otherwise use old heuristic.
  938. if (all is not None or
  939. inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  940. if visiblename(key, all, object):
  941. funcs.append((key, value))
  942. data = []
  943. for key, value in inspect.getmembers(object, isdata):
  944. if visiblename(key, all, object):
  945. data.append((key, value))
  946. modpkgs = []
  947. modpkgs_names = set()
  948. if hasattr(object, '__path__'):
  949. for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  950. modpkgs_names.add(modname)
  951. if ispkg:
  952. modpkgs.append(modname + ' (package)')
  953. else:
  954. modpkgs.append(modname)
  955. modpkgs.sort()
  956. result = result + self.section(
  957. 'PACKAGE CONTENTS', join(modpkgs, '\n'))
  958. # Detect submodules as sometimes created by C extensions
  959. submodules = []
  960. for key, value in inspect.getmembers(object, inspect.ismodule):
  961. if value.__name__.startswith(name + '.') and key not in modpkgs_names:
  962. submodules.append(key)
  963. if submodules:
  964. submodules.sort()
  965. result = result + self.section(
  966. 'SUBMODULES', join(submodules, '\n'))
  967. if classes:
  968. classlist = map(lambda key_value: key_value[1], classes)
  969. contents = [self.formattree(
  970. inspect.getclasstree(classlist, 1), name)]
  971. for key, value in classes:
  972. contents.append(self.document(value, key, name))
  973. result = result + self.section('CLASSES', join(contents, '\n'))
  974. if funcs:
  975. contents = []
  976. for key, value in funcs:
  977. contents.append(self.document(value, key, name))
  978. result = result + self.section('FUNCTIONS', join(contents, '\n'))
  979. if data:
  980. contents = []
  981. for key, value in data:
  982. contents.append(self.docother(value, key, name, maxlen=70))
  983. result = result + self.section('DATA', join(contents, '\n'))
  984. if hasattr(object, '__version__'):
  985. version = str(object.__version__)
  986. if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  987. version = strip(version[11:-1])
  988. result = result + self.section('VERSION', version)
  989. if hasattr(object, '__date__'):
  990. result = result + self.section('DATE', str(object.__date__))
  991. if hasattr(object, '__author__'):
  992. result = result + self.section('AUTHOR', str(object.__author__))
  993. if hasattr(object, '__credits__'):
  994. result = result + self.section('CREDITS', str(object.__credits__))
  995. return result
  996. def docclass(self, object, name=None, mod=None, *ignored):
  997. """Produce text documentation for a given class object."""
  998. realname = object.__name__
  999. name = name or realname
  1000. bases = object.__bases__
  1001. def makename(c, m=object.__module__):
  1002. return classname(c, m)
  1003. if name == realname:
  1004. title = 'class ' + self.bold(realname)
  1005. else:
  1006. title = self.bold(name) + ' = class ' + realname
  1007. if bases:
  1008. parents = map(makename, bases)
  1009. title = title + '(%s)' % join(parents, ', ')
  1010. doc = getdoc(object)
  1011. contents = doc and [doc + '\n'] or []
  1012. push = contents.append
  1013. # List the mro, if non-trivial.
  1014. mro = deque(inspect.getmro(object))
  1015. if len(mro) > 2:
  1016. push("Method resolution order:")
  1017. for base in mro:
  1018. push(' ' + makename(base))
  1019. push('')
  1020. # Cute little class to pump out a horizontal rule between sections.
  1021. class HorizontalRule:
  1022. def __init__(self):
  1023. self.needone = 0
  1024. def maybe(self):
  1025. if self.needone:
  1026. push('-' * 70)
  1027. self.needone = 1
  1028. hr = HorizontalRule()
  1029. def spill(msg, attrs, predicate):
  1030. ok, attrs = _split_list(attrs, predicate)
  1031. if ok:
  1032. hr.maybe()
  1033. push(msg)
  1034. for name, kind, homecls, value in ok:
  1035. try:
  1036. value = getattr(object, name)
  1037. except Exception:
  1038. # Some descriptors may meet a failure in their __get__.
  1039. # (bug #1785)
  1040. push(self._docdescriptor(name, value, mod))
  1041. else:
  1042. push(self.document(value,
  1043. name, mod, object))
  1044. return attrs
  1045. def spilldescriptors(msg, attrs, predicate):
  1046. ok, attrs = _split_list(attrs, predicate)
  1047. if ok:
  1048. hr.maybe()
  1049. push(msg)
  1050. for name, kind, homecls, value in ok:
  1051. push(self._docdescriptor(name, value, mod))
  1052. return attrs
  1053. def spilldata(msg, attrs, predicate):
  1054. ok, attrs = _split_list(attrs, predicate)
  1055. if ok:
  1056. hr.maybe()
  1057. push(msg)
  1058. for name, kind, homecls, value in ok:
  1059. if (hasattr(value, '__call__') or
  1060. inspect.isdatadescriptor(value)):
  1061. doc = getdoc(value)
  1062. else:
  1063. doc = None
  1064. push(self.docother(getattr(object, name),
  1065. name, mod, maxlen=70, doc=doc) + '\n')
  1066. return attrs
  1067. attrs = filter(lambda data: visiblename(data[0], obj=object),
  1068. classify_class_attrs(object))
  1069. while attrs:
  1070. if mro:
  1071. thisclass = mro.popleft()
  1072. else:
  1073. thisclass = attrs[0][2]
  1074. attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  1075. if thisclass is __builtin__.object:
  1076. attrs = inherited
  1077. continue
  1078. elif thisclass is object:
  1079. tag = "defined here"
  1080. else:
  1081. tag = "inherited from %s" % classname(thisclass,
  1082. object.__module__)
  1083. # Sort attrs by name.
  1084. attrs.sort()
  1085. # Pump out the attrs, segregated by kind.
  1086. attrs = spill("Methods %s:\n" % tag, attrs,
  1087. lambda t: t[1] == 'method')
  1088. attrs = spill("Class methods %s:\n" % tag, attrs,
  1089. lambda t: t[1] == 'class method')
  1090. attrs = spill("Static methods %s:\n" % tag, attrs,
  1091. lambda t: t[1] == 'static method')
  1092. attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
  1093. lambda t: t[1] == 'data de…

Large files files are truncated, but you can click here to view the full file