PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/pydoc.py

https://bitbucket.org/mirror/python-release25-maint
Python | 2256 lines | 2197 code | 39 blank | 20 comment | 122 complexity | 7310ba0bb55d24f0d3be7b152bfa5666 MD5 | raw file
Possible License(s): 0BSD

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

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