PageRenderTime 68ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/pydoc.py

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

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