PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/setuptools/pydoc.py

https://bitbucket.org/ionelmc/juicer-pylons
Python | 2232 lines | 2173 code | 39 blank | 20 comment | 122 complexity | d5e0a11b6115e95eb33c6b9138d17081 MD5 | raw file

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

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

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