blob: 1369e8a5f85c9934dd5bed99d117a073ea7f70f6 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002"""Generate Python documentation in HTML or text for interactive use.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00003
Georg Brandlc645c6a2012-06-24 17:24:26 +02004In the Python interpreter, do "from pydoc import help" to provide
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00005help. Calling help(thing) on a Python object documents the object.
6
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00007Or, at the shell command line outside of Python:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00008
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00009Run "pydoc <name>" to show documentation on something. <name> may be
10the name of a function, module, package, or a dotted reference to a
11class or function within a module or module in a package. If the
12argument contains a path segment delimiter (e.g. slash on Unix,
13backslash on Windows) it is treated as the path to a Python source file.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000014
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000015Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
16of all available modules.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000017
Nick Coghlan7bb30b72010-12-03 09:29:11 +000018Run "pydoc -p <port>" to start an HTTP server on the given port on the
19local machine. Port number 0 can be used to get an arbitrary unused port.
20
21Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
22open a Web browser to interactively browse documentation. The -p option
23can be used with the -b option to explicitly specify the server port.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000024
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000025Run "pydoc -w <name>" to write out the HTML documentation for a module
26to a file named "<name>.html".
Skip Montanaro4997a692003-09-10 16:47:51 +000027
28Module docs for core modules are assumed to be in
29
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000030 http://docs.python.org/X.Y/library/
Skip Montanaro4997a692003-09-10 16:47:51 +000031
32This can be overridden by setting the PYTHONDOCS environment variable
33to a different URL or to a local directory containing the Library
34Reference Manual pages.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000035"""
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000036__all__ = ['help']
Ka-Ping Yeedd175342001-02-27 14:43:46 +000037__author__ = "Ka-Ping Yee <ping@lfw.org>"
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000038__date__ = "26 February 2001"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000039
Martin v. Löwis6fe8f192004-11-14 10:21:04 +000040__credits__ = """Guido van Rossum, for an excellent programming language.
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000041Tommy Burnette, the original creator of manpy.
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000042Paul Prescod, for all his work on onlinehelp.
43Richard Chamberlain, for the first implementation of textdoc.
Raymond Hettingered2dbe32005-01-01 07:51:01 +000044"""
Ka-Ping Yeedd175342001-02-27 14:43:46 +000045
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000046# Known bugs that can't be fixed here:
Brett Cannonf4ba4ec2013-06-15 14:25:04 -040047# - synopsis() cannot be prevented from clobbering existing
48# loaded modules.
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000049# - If the __file__ attribute on a module is a relative path and
50# the current directory is changed with os.chdir(), an incorrect
51# path will be displayed.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000052
Nick Coghlan7bb30b72010-12-03 09:29:11 +000053import builtins
Brett Cannond5e6f2e2013-06-11 17:09:36 -040054import importlib._bootstrap
Brett Cannoncb66eb02012-05-11 12:58:42 -040055import importlib.machinery
Brett Cannonf4ba4ec2013-06-15 14:25:04 -040056import importlib.util
Nick Coghlan7bb30b72010-12-03 09:29:11 +000057import inspect
Victor Stinnere6c910e2011-06-30 15:55:43 +020058import io
59import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +000060import pkgutil
61import platform
62import re
Victor Stinnere6c910e2011-06-30 15:55:43 +020063import sys
Nick Coghlan7bb30b72010-12-03 09:29:11 +000064import time
Victor Stinnere6c910e2011-06-30 15:55:43 +020065import tokenize
Nick Coghlan7bb30b72010-12-03 09:29:11 +000066import warnings
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000067from collections import deque
Nick Coghlan7bb30b72010-12-03 09:29:11 +000068from reprlib import Repr
Georg Brandld2f38572011-01-30 08:37:19 +000069from traceback import extract_tb, format_exception_only
Nick Coghlan7bb30b72010-12-03 09:29:11 +000070
71
Ka-Ping Yeedd175342001-02-27 14:43:46 +000072# --------------------------------------------------------- common routines
73
Ka-Ping Yeedd175342001-02-27 14:43:46 +000074def pathdirs():
75 """Convert sys.path into a list of absolute, existing, unique paths."""
76 dirs = []
Ka-Ping Yee1d384632001-03-01 00:24:32 +000077 normdirs = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +000078 for dir in sys.path:
79 dir = os.path.abspath(dir or '.')
Ka-Ping Yee1d384632001-03-01 00:24:32 +000080 normdir = os.path.normcase(dir)
81 if normdir not in normdirs and os.path.isdir(dir):
Ka-Ping Yeedd175342001-02-27 14:43:46 +000082 dirs.append(dir)
Ka-Ping Yee1d384632001-03-01 00:24:32 +000083 normdirs.append(normdir)
Ka-Ping Yeedd175342001-02-27 14:43:46 +000084 return dirs
85
86def getdoc(object):
87 """Get the doc string or comments for an object."""
Ka-Ping Yee3bda8792001-03-23 13:17:50 +000088 result = inspect.getdoc(object) or inspect.getcomments(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +000089 return result and re.sub('^ *\n', '', result.rstrip()) or ''
Ka-Ping Yeedd175342001-02-27 14:43:46 +000090
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000091def splitdoc(doc):
92 """Split a doc string into a synopsis line (if any) and the rest."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +000093 lines = doc.strip().split('\n')
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000094 if len(lines) == 1:
95 return lines[0], ''
Neal Norwitz9d72bb42007-04-17 08:48:32 +000096 elif len(lines) >= 2 and not lines[1].rstrip():
97 return lines[0], '\n'.join(lines[2:])
98 return '', '\n'.join(lines)
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000099
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000100def classname(object, modname):
101 """Get a class name and qualify it with a module name if necessary."""
102 name = object.__name__
103 if object.__module__ != modname:
104 name = object.__module__ + '.' + name
105 return name
106
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000107def isdata(object):
Georg Brandl94432422005-07-22 21:52:25 +0000108 """Check if an object is of a type that probably means it's data."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000109 return not (inspect.ismodule(object) or inspect.isclass(object) or
110 inspect.isroutine(object) or inspect.isframe(object) or
111 inspect.istraceback(object) or inspect.iscode(object))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000112
113def replace(text, *pairs):
114 """Do a series of global replacements on a string."""
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000115 while pairs:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000116 text = pairs[1].join(text.split(pairs[0]))
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000117 pairs = pairs[2:]
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000118 return text
119
120def cram(text, maxlen):
121 """Omit part of a string if needed to make it fit in a maximum length."""
122 if len(text) > maxlen:
Raymond Hettingerfca3bb62002-10-21 04:44:11 +0000123 pre = max(0, (maxlen-3)//2)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000124 post = max(0, maxlen-3-pre)
125 return text[:pre] + '...' + text[len(text)-post:]
126 return text
127
Brett Cannon84601f12004-06-19 01:22:48 +0000128_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000129def stripid(text):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000130 """Remove the hexadecimal id from a Python object representation."""
Brett Cannonc6c1f472004-06-19 01:02:51 +0000131 # The behaviour of %p is implementation-dependent in terms of case.
Ezio Melotti412c95a2010-02-16 23:31:04 +0000132 return _re_stripid.sub(r'\1', text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000133
Brett Cannonc6c1f472004-06-19 01:02:51 +0000134def _is_some_method(obj):
R David Murrayac0cea52013-03-19 02:47:44 -0400135 return (inspect.isfunction(obj) or
136 inspect.ismethod(obj) or
137 inspect.isbuiltin(obj) or
138 inspect.ismethoddescriptor(obj))
Tim Peters536d2262001-09-20 05:13:38 +0000139
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000140def allmethods(cl):
141 methods = {}
Tim Peters536d2262001-09-20 05:13:38 +0000142 for key, value in inspect.getmembers(cl, _is_some_method):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000143 methods[key] = 1
144 for base in cl.__bases__:
145 methods.update(allmethods(base)) # all your base are belong to us
146 for key in methods.keys():
147 methods[key] = getattr(cl, key)
148 return methods
149
Tim Petersfa26f7c2001-09-24 08:05:11 +0000150def _split_list(s, predicate):
151 """Split sequence s via predicate, and return pair ([true], [false]).
152
153 The return value is a 2-tuple of lists,
154 ([x for x in s if predicate(x)],
155 [x for x in s if not predicate(x)])
156 """
157
Tim Peters28355492001-09-23 21:29:55 +0000158 yes = []
159 no = []
Tim Petersfa26f7c2001-09-24 08:05:11 +0000160 for x in s:
161 if predicate(x):
162 yes.append(x)
Tim Peters28355492001-09-23 21:29:55 +0000163 else:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000164 no.append(x)
Tim Peters28355492001-09-23 21:29:55 +0000165 return yes, no
166
Raymond Hettinger1103d052011-03-25 14:15:24 -0700167def visiblename(name, all=None, obj=None):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000168 """Decide whether to show documentation on a variable."""
Brett Cannond340b432012-08-06 17:19:22 -0400169 # Certain special names are redundant or internal.
Eric Snowb523f842013-11-22 09:05:39 -0700170 # XXX Remove __initializing__?
Brett Cannond340b432012-08-06 17:19:22 -0400171 if name in {'__author__', '__builtins__', '__cached__', '__credits__',
Eric Snowb523f842013-11-22 09:05:39 -0700172 '__date__', '__doc__', '__file__', '__spec__',
Brett Cannond340b432012-08-06 17:19:22 -0400173 '__loader__', '__module__', '__name__', '__package__',
174 '__path__', '__qualname__', '__slots__', '__version__'}:
Raymond Hettinger68272942011-03-18 02:22:15 -0700175 return 0
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000176 # Private names are hidden, but special names are displayed.
177 if name.startswith('__') and name.endswith('__'): return 1
Raymond Hettinger1103d052011-03-25 14:15:24 -0700178 # Namedtuples have public fields and methods with a single leading underscore
179 if name.startswith('_') and hasattr(obj, '_fields'):
180 return True
Skip Montanaroa5616d22004-06-11 04:46:12 +0000181 if all is not None:
182 # only document that which the programmer exported in __all__
183 return name in all
184 else:
185 return not name.startswith('_')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000186
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000187def classify_class_attrs(object):
188 """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000189 results = []
190 for (name, kind, cls, value) in inspect.classify_class_attrs(object):
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000191 if inspect.isdatadescriptor(value):
192 kind = 'data descriptor'
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000193 results.append((name, kind, cls, value))
194 return results
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000195
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000196# ----------------------------------------------------- module manipulation
197
198def ispackage(path):
199 """Guess whether a path refers to a package directory."""
200 if os.path.isdir(path):
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000201 for ext in ('.py', '.pyc', '.pyo'):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000202 if os.path.isfile(os.path.join(path, '__init__' + ext)):
Tim Petersbc0e9102002-04-04 22:55:58 +0000203 return True
204 return False
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000205
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206def source_synopsis(file):
207 line = file.readline()
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000208 while line[:1] == '#' or not line.strip():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209 line = file.readline()
210 if not line: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000211 line = line.strip()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 if line[:4] == 'r"""': line = line[1:]
213 if line[:3] == '"""':
214 line = line[3:]
215 if line[-1:] == '\\': line = line[:-1]
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000216 while not line.strip():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217 line = file.readline()
218 if not line: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000219 result = line.split('"""')[0].strip()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220 else: result = None
221 return result
222
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000223def synopsis(filename, cache={}):
224 """Get the one-line summary out of a module file."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000225 mtime = os.stat(filename).st_mtime
Charles-François Natali27c4e882011-07-27 19:40:02 +0200226 lastupdate, result = cache.get(filename, (None, None))
227 if lastupdate is None or lastupdate < mtime:
Eric Snowaed5b222014-01-04 20:38:11 -0700228 # Look for binary suffixes first, falling back to source.
229 if filename.endswith(tuple(importlib.machinery.BYTECODE_SUFFIXES)):
230 loader_cls = importlib.machinery.SourcelessFileLoader
231 elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
232 loader_cls = importlib.machinery.ExtensionFileLoader
233 else:
234 loader_cls = None
235 # Now handle the choice.
236 if loader_cls is None:
237 # Must be a source file.
238 try:
239 file = tokenize.open(filename)
240 except OSError:
241 # module can't be opened, so skip it
242 return None
243 # text modules can be directly examined
244 with file:
245 result = source_synopsis(file)
246 else:
247 # Must be a binary module, which has to be imported.
248 loader = loader_cls('__temp__', filename)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400249 try:
250 module = loader.load_module('__temp__')
251 except:
252 return None
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000253 del sys.modules['__temp__']
Eric Snowaed5b222014-01-04 20:38:11 -0700254 result = (module.__doc__ or '').splitlines()[0]
255 # Cache the result.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000256 cache[filename] = (mtime, result)
257 return result
258
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000259class ErrorDuringImport(Exception):
260 """Errors that occurred while trying to import something to document it."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000261 def __init__(self, filename, exc_info):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000262 self.filename = filename
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000263 self.exc, self.value, self.tb = exc_info
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000264
265 def __str__(self):
Guido van Rossuma01a8b62007-05-27 09:20:14 +0000266 exc = self.exc.__name__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000267 return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000268
269def importfile(path):
270 """Import a Python source file or compiled file given its path."""
Brett Cannonf4ba4ec2013-06-15 14:25:04 -0400271 magic = importlib.util.MAGIC_NUMBER
Victor Stinnere975af62011-07-04 02:08:50 +0200272 with open(path, 'rb') as file:
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400273 is_bytecode = magic == file.read(len(magic))
274 filename = os.path.basename(path)
275 name, ext = os.path.splitext(filename)
276 if is_bytecode:
277 loader = importlib._bootstrap.SourcelessFileLoader(name, path)
278 else:
279 loader = importlib._bootstrap.SourceFileLoader(name, path)
280 try:
281 return loader.load_module(name)
282 except:
283 raise ErrorDuringImport(path, sys.exc_info())
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000284
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000285def safeimport(path, forceload=0, cache={}):
286 """Import a module; handle errors; return None if the module isn't found.
287
288 If the module *is* found but an exception occurs, it's wrapped in an
289 ErrorDuringImport exception and reraised. Unlike __import__, if a
290 package path is specified, the module at the end of the path is returned,
291 not the package at the beginning. If the optional 'forceload' argument
292 is 1, we reload the module from disk (unless it's a dynamic extension)."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000293 try:
Ka-Ping Yee9a2dcf82005-11-05 05:04:41 +0000294 # If forceload is 1 and the module has been previously loaded from
295 # disk, we always have to reload the module. Checking the file's
296 # mtime isn't good enough (e.g. the module could contain a class
297 # that inherits from another module that has changed).
298 if forceload and path in sys.modules:
299 if path not in sys.builtin_module_names:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000300 # Remove the module from sys.modules and re-import to try
301 # and avoid problems with partially loaded modules.
302 # Also remove any submodules because they won't appear
303 # in the newly loaded module's namespace if they're already
304 # in sys.modules.
Ka-Ping Yee9a2dcf82005-11-05 05:04:41 +0000305 subs = [m for m in sys.modules if m.startswith(path + '.')]
306 for key in [path] + subs:
307 # Prevent garbage collection.
308 cache[key] = sys.modules[key]
309 del sys.modules[key]
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000310 module = __import__(path)
311 except:
312 # Did the error occur before or after the module was found?
313 (exc, value, tb) = info = sys.exc_info()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000314 if path in sys.modules:
Fred Drakedb390c12005-10-28 14:39:47 +0000315 # An error occurred while executing the imported module.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000316 raise ErrorDuringImport(sys.modules[path].__file__, info)
317 elif exc is SyntaxError:
318 # A SyntaxError occurred before we could execute the module.
319 raise ErrorDuringImport(value.filename, info)
Brett Cannon679ecb52013-07-04 17:51:50 -0400320 elif exc is ImportError and value.name == path:
Brett Cannonfd074152012-04-14 14:10:13 -0400321 # No such module in the path.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000322 return None
323 else:
324 # Some other error occurred during the importing process.
325 raise ErrorDuringImport(path, sys.exc_info())
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000326 for part in path.split('.')[1:]:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000327 try: module = getattr(module, part)
328 except AttributeError: return None
329 return module
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000330
331# ---------------------------------------------------- formatter base class
332
333class Doc:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000334
335 PYTHONDOCS = os.environ.get("PYTHONDOCS",
336 "http://docs.python.org/%d.%d/library"
337 % sys.version_info[:2])
338
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000339 def document(self, object, name=None, *args):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000340 """Generate documentation for an object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000341 args = (object, name) + args
Brett Cannon28a4f0f2003-06-11 23:38:55 +0000342 # 'try' clause is to attempt to handle the possibility that inspect
343 # identifies something in a way that pydoc itself has issues handling;
344 # think 'super' and how it is a descriptor (which raises the exception
345 # by lacking a __name__ attribute) and an instance.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000346 if inspect.isgetsetdescriptor(object): return self.docdata(*args)
347 if inspect.ismemberdescriptor(object): return self.docdata(*args)
Brett Cannon28a4f0f2003-06-11 23:38:55 +0000348 try:
349 if inspect.ismodule(object): return self.docmodule(*args)
350 if inspect.isclass(object): return self.docclass(*args)
351 if inspect.isroutine(object): return self.docroutine(*args)
352 except AttributeError:
353 pass
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000354 if isinstance(object, property): return self.docproperty(*args)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000355 return self.docother(*args)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000356
357 def fail(self, object, name=None, *args):
358 """Raise an exception for unimplemented types."""
359 message = "don't know how to document object%s of type %s" % (
360 name and ' ' + repr(name), type(object).__name__)
Collin Winterce36ad82007-08-30 01:19:48 +0000361 raise TypeError(message)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000362
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000363 docmodule = docclass = docroutine = docother = docproperty = docdata = fail
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000364
Skip Montanaro4997a692003-09-10 16:47:51 +0000365 def getdocloc(self, object):
366 """Return the location of module docs or None"""
367
368 try:
369 file = inspect.getabsfile(object)
370 except TypeError:
371 file = '(built-in)'
372
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000373 docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
374
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100375 basedir = os.path.join(sys.base_exec_prefix, "lib",
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000376 "python%d.%d" % sys.version_info[:2])
Skip Montanaro4997a692003-09-10 16:47:51 +0000377 if (isinstance(object, type(os)) and
378 (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
379 'marshal', 'posix', 'signal', 'sys',
Georg Brandl2067bfd2008-05-25 13:05:15 +0000380 '_thread', 'zipimport') or
Skip Montanaro4997a692003-09-10 16:47:51 +0000381 (file.startswith(basedir) and
Brian Curtin49c284c2010-03-31 03:19:28 +0000382 not file.startswith(os.path.join(basedir, 'site-packages')))) and
Brian Curtinedef05b2010-04-01 04:05:25 +0000383 object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
Skip Montanaro4997a692003-09-10 16:47:51 +0000384 if docloc.startswith("http://"):
Georg Brandl86def6c2008-01-21 20:36:10 +0000385 docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
Skip Montanaro4997a692003-09-10 16:47:51 +0000386 else:
Georg Brandl86def6c2008-01-21 20:36:10 +0000387 docloc = os.path.join(docloc, object.__name__ + ".html")
Skip Montanaro4997a692003-09-10 16:47:51 +0000388 else:
389 docloc = None
390 return docloc
391
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000392# -------------------------------------------- HTML documentation generator
393
394class HTMLRepr(Repr):
395 """Class for safely making an HTML representation of a Python object."""
396 def __init__(self):
397 Repr.__init__(self)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000398 self.maxlist = self.maxtuple = 20
399 self.maxdict = 10
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000400 self.maxstring = self.maxother = 100
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000401
402 def escape(self, text):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000403 return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000404
405 def repr(self, object):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000406 return Repr.repr(self, object)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000407
408 def repr1(self, x, level):
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000409 if hasattr(type(x), '__name__'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000410 methodname = 'repr_' + '_'.join(type(x).__name__.split())
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000411 if hasattr(self, methodname):
412 return getattr(self, methodname)(x, level)
413 return self.escape(cram(stripid(repr(x)), self.maxother))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000414
415 def repr_string(self, x, level):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000416 test = cram(x, self.maxstring)
417 testrepr = repr(test)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000418 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000419 # Backslashes are only literal in the string and are never
420 # needed to make any special characters, so show a raw string.
421 return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000422 return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000423 r'<font color="#c040c0">\1</font>',
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000424 self.escape(testrepr))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000425
Skip Montanarodf708782002-03-07 22:58:02 +0000426 repr_str = repr_string
427
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000428 def repr_instance(self, x, level):
429 try:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000430 return self.escape(cram(stripid(repr(x)), self.maxstring))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000431 except:
432 return self.escape('<%s instance>' % x.__class__.__name__)
433
434 repr_unicode = repr_string
435
436class HTMLDoc(Doc):
437 """Formatter class for HTML documentation."""
438
439 # ------------------------------------------- HTML formatting utilities
440
441 _repr_instance = HTMLRepr()
442 repr = _repr_instance.repr
443 escape = _repr_instance.escape
444
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000445 def page(self, title, contents):
446 """Format an HTML page."""
Georg Brandl388faac2009-04-10 08:31:48 +0000447 return '''\
Georg Brandle6066942009-04-10 08:28:28 +0000448<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000449<html><head><title>Python: %s</title>
Georg Brandl388faac2009-04-10 08:31:48 +0000450<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000451</head><body bgcolor="#f0f0f8">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000452%s
453</body></html>''' % (title, contents)
454
455 def heading(self, title, fgcol, bgcol, extras=''):
456 """Format a page heading."""
457 return '''
Tim Peters59ed4482001-10-31 04:20:26 +0000458<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000459<tr bgcolor="%s">
Tim Peters2306d242001-09-25 03:18:32 +0000460<td valign=bottom>&nbsp;<br>
461<font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000462><td align=right valign=bottom
Ka-Ping Yee987ec902001-03-23 13:35:45 +0000463><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000464 ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
465
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000466 def section(self, title, fgcol, bgcol, contents, width=6,
467 prelude='', marginalia=None, gap='&nbsp;'):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000468 """Format a section with a heading."""
469 if marginalia is None:
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000470 marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000471 result = '''<p>
Tim Peters59ed4482001-10-31 04:20:26 +0000472<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000473<tr bgcolor="%s">
Tim Peters2306d242001-09-25 03:18:32 +0000474<td colspan=3 valign=bottom>&nbsp;<br>
475<font color="%s" face="helvetica, arial">%s</font></td></tr>
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000476 ''' % (bgcol, fgcol, title)
477 if prelude:
478 result = result + '''
Ka-Ping Yee987ec902001-03-23 13:35:45 +0000479<tr bgcolor="%s"><td rowspan=2>%s</td>
480<td colspan=2>%s</td></tr>
481<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
482 else:
483 result = result + '''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000484<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000485
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000486 return result + '\n<td width="100%%">%s</td></tr></table>' % contents
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000487
488 def bigsection(self, title, *args):
489 """Format a section with a big heading."""
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000490 title = '<big><strong>%s</strong></big>' % title
Guido van Rossum68468eb2003-02-27 20:14:51 +0000491 return self.section(title, *args)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000492
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000493 def preformat(self, text):
494 """Format literal preformatted text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000495 text = self.escape(text.expandtabs())
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000496 return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
497 ' ', '&nbsp;', '\n', '<br>\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000498
499 def multicolumn(self, list, format, cols=4):
500 """Format a list of items into a multi-column list."""
501 result = ''
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000502 rows = (len(list)+cols-1)//cols
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000503 for col in range(cols):
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000504 result = result + '<td width="%d%%" valign=top>' % (100//cols)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000505 for i in range(rows*col, rows*col+rows):
506 if i < len(list):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000507 result = result + format(list[i]) + '<br>\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000508 result = result + '</td>'
Tim Peters59ed4482001-10-31 04:20:26 +0000509 return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000510
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000511 def grey(self, text): return '<font color="#909090">%s</font>' % text
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000512
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000513 def namelink(self, name, *dicts):
514 """Make a link for an identifier, given name-to-URL mappings."""
515 for dict in dicts:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000516 if name in dict:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000517 return '<a href="%s">%s</a>' % (dict[name], name)
518 return name
519
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000520 def classlink(self, object, modname):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000521 """Make a link for a class."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000522 name, module = object.__name__, sys.modules.get(object.__module__)
523 if hasattr(module, name) and getattr(module, name) is object:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000524 return '<a href="%s.html#%s">%s</a>' % (
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000525 module.__name__, name, classname(object, modname))
526 return classname(object, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000527
528 def modulelink(self, object):
529 """Make a link for a module."""
530 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
531
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000532 def modpkglink(self, modpkginfo):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000533 """Make a link for a module or package to display in an index."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000534 name, path, ispackage, shadowed = modpkginfo
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000535 if shadowed:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000536 return self.grey(name)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000537 if path:
538 url = '%s.%s.html' % (path, name)
539 else:
540 url = '%s.html' % name
541 if ispackage:
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000542 text = '<strong>%s</strong>&nbsp;(package)' % name
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000543 else:
544 text = name
545 return '<a href="%s">%s</a>' % (url, text)
546
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000547 def filelink(self, url, path):
548 """Make a link to source file."""
549 return '<a href="file:%s">%s</a>' % (url, path)
550
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000551 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
552 """Mark up some plain text, given a context of symbols to look for.
553 Each context dictionary maps object names to anchor names."""
554 escape = escape or self.escape
555 results = []
556 here = 0
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000557 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
558 r'RFC[- ]?(\d+)|'
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000559 r'PEP[- ]?(\d+)|'
Neil Schemenauerd69711c2002-03-24 23:02:07 +0000560 r'(self\.)?(\w+))')
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000561 while True:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000562 match = pattern.search(text, here)
563 if not match: break
564 start, end = match.span()
565 results.append(escape(text[here:start]))
566
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000567 all, scheme, rfc, pep, selfdot, name = match.groups()
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000568 if scheme:
Neil Schemenauercddc1a02002-03-24 23:11:21 +0000569 url = escape(all).replace('"', '&quot;')
570 results.append('<a href="%s">%s</a>' % (url, url))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000571 elif rfc:
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000572 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
573 results.append('<a href="%s">%s</a>' % (url, escape(all)))
574 elif pep:
Christian Heimes2202f872008-02-06 14:31:34 +0000575 url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000576 results.append('<a href="%s">%s</a>' % (url, escape(all)))
577 elif text[end:end+1] == '(':
578 results.append(self.namelink(name, methods, funcs, classes))
579 elif selfdot:
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000580 results.append('self.<strong>%s</strong>' % name)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000581 else:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000582 results.append(self.namelink(name, classes))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000583 here = end
584 results.append(escape(text[here:]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000585 return ''.join(results)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000586
587 # ---------------------------------------------- type-specific routines
588
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000589 def formattree(self, tree, modname, parent=None):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000590 """Produce HTML for a class tree as given by inspect.getclasstree()."""
591 result = ''
592 for entry in tree:
593 if type(entry) is type(()):
594 c, bases = entry
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000595 result = result + '<dt><font face="helvetica, arial">'
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000596 result = result + self.classlink(c, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000597 if bases and bases != (parent,):
598 parents = []
599 for base in bases:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000600 parents.append(self.classlink(base, modname))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000601 result = result + '(' + ', '.join(parents) + ')'
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000602 result = result + '\n</font></dt>'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000603 elif type(entry) is type([]):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000604 result = result + '<dd>\n%s</dd>\n' % self.formattree(
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000605 entry, modname, c)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000606 return '<dl>\n%s</dl>\n' % result
607
Tim Peters8dd7ade2001-10-18 19:56:17 +0000608 def docmodule(self, object, name=None, mod=None, *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000609 """Produce HTML documentation for a module object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000610 name = object.__name__ # ignore the passed-in name
Skip Montanaroa5616d22004-06-11 04:46:12 +0000611 try:
612 all = object.__all__
613 except AttributeError:
614 all = None
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000615 parts = name.split('.')
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000616 links = []
617 for i in range(len(parts)-1):
618 links.append(
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000619 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000620 ('.'.join(parts[:i+1]), parts[i]))
621 linkedname = '.'.join(links + parts[-1:])
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000622 head = '<big><big><strong>%s</strong></big></big>' % linkedname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000623 try:
Ka-Ping Yee239432a2001-03-02 02:45:08 +0000624 path = inspect.getabsfile(object)
Ka-Ping Yee6191a232001-04-13 15:00:27 +0000625 url = path
626 if sys.platform == 'win32':
627 import nturl2path
628 url = nturl2path.pathname2url(path)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000629 filelink = self.filelink(url, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000630 except TypeError:
631 filelink = '(built-in)'
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000632 info = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000633 if hasattr(object, '__version__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000634 version = str(object.__version__)
Ka-Ping Yee40c49912001-02-27 22:46:01 +0000635 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000636 version = version[11:-1].strip()
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000637 info.append('version %s' % self.escape(version))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000638 if hasattr(object, '__date__'):
639 info.append(self.escape(str(object.__date__)))
640 if info:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000641 head = head + ' (%s)' % ', '.join(info)
Skip Montanaro4997a692003-09-10 16:47:51 +0000642 docloc = self.getdocloc(object)
643 if docloc is not None:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000644 docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals()
Skip Montanaro4997a692003-09-10 16:47:51 +0000645 else:
646 docloc = ''
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000647 result = self.heading(
Skip Montanaro4997a692003-09-10 16:47:51 +0000648 head, '#ffffff', '#7799ee',
649 '<a href=".">index</a><br>' + filelink + docloc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000650
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000651 modules = inspect.getmembers(object, inspect.ismodule)
652
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000653 classes, cdict = [], {}
654 for key, value in inspect.getmembers(object, inspect.isclass):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +0000655 # if __all__ exists, believe it. Otherwise use old heuristic.
656 if (all is not None or
657 (inspect.getmodule(value) or object) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700658 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000659 classes.append((key, value))
660 cdict[key] = cdict[value] = '#' + key
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000661 for key, value in classes:
662 for base in value.__bases__:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000663 key, modname = base.__name__, base.__module__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000664 module = sys.modules.get(modname)
665 if modname != name and module and hasattr(module, key):
666 if getattr(module, key) is base:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000667 if not key in cdict:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000668 cdict[key] = cdict[base] = modname + '.html#' + key
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000669 funcs, fdict = [], {}
670 for key, value in inspect.getmembers(object, inspect.isroutine):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +0000671 # if __all__ exists, believe it. Otherwise use old heuristic.
672 if (all is not None or
673 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700674 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000675 funcs.append((key, value))
676 fdict[key] = '#-' + key
677 if inspect.isfunction(value): fdict[value] = fdict[key]
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000678 data = []
679 for key, value in inspect.getmembers(object, isdata):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700680 if visiblename(key, all, object):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000681 data.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000682
683 doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
684 doc = doc and '<tt>%s</tt>' % doc
Tim Peters2306d242001-09-25 03:18:32 +0000685 result = result + '<p>%s</p>\n' % doc
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000686
687 if hasattr(object, '__path__'):
688 modpkgs = []
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000689 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
690 modpkgs.append((modname, name, ispkg, 0))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000691 modpkgs.sort()
692 contents = self.multicolumn(modpkgs, self.modpkglink)
693 result = result + self.bigsection(
694 'Package Contents', '#ffffff', '#aa55cc', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000695 elif modules:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000696 contents = self.multicolumn(
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000697 modules, lambda t: self.modulelink(t[1]))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000698 result = result + self.bigsection(
Christian Heimes7131fd92008-02-19 14:21:46 +0000699 'Modules', '#ffffff', '#aa55cc', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000700
701 if classes:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000702 classlist = [value for (key, value) in classes]
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000703 contents = [
704 self.formattree(inspect.getclasstree(classlist, 1), name)]
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000705 for key, value in classes:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000706 contents.append(self.document(value, key, name, fdict, cdict))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000707 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000708 'Classes', '#ffffff', '#ee77aa', ' '.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000709 if funcs:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000710 contents = []
711 for key, value in funcs:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000712 contents.append(self.document(value, key, name, fdict, cdict))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000713 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000714 'Functions', '#ffffff', '#eeaa77', ' '.join(contents))
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000715 if data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000716 contents = []
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000717 for key, value in data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000718 contents.append(self.document(value, key))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000719 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000720 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000721 if hasattr(object, '__author__'):
722 contents = self.markup(str(object.__author__), self.preformat)
723 result = result + self.bigsection(
724 'Author', '#ffffff', '#7799ee', contents)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000725 if hasattr(object, '__credits__'):
726 contents = self.markup(str(object.__credits__), self.preformat)
727 result = result + self.bigsection(
728 'Credits', '#ffffff', '#7799ee', contents)
729
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000730 return result
731
Tim Peters8dd7ade2001-10-18 19:56:17 +0000732 def docclass(self, object, name=None, mod=None, funcs={}, classes={},
733 *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000734 """Produce HTML documentation for a class object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000735 realname = object.__name__
736 name = name or realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000737 bases = object.__bases__
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000738
Tim Petersb47879b2001-09-24 04:47:19 +0000739 contents = []
740 push = contents.append
741
Tim Petersfa26f7c2001-09-24 08:05:11 +0000742 # Cute little class to pump out a horizontal rule between sections.
743 class HorizontalRule:
744 def __init__(self):
745 self.needone = 0
746 def maybe(self):
747 if self.needone:
748 push('<hr>\n')
749 self.needone = 1
750 hr = HorizontalRule()
751
Tim Petersc86f6ca2001-09-26 21:31:51 +0000752 # List the mro, if non-trivial.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000753 mro = deque(inspect.getmro(object))
Tim Petersc86f6ca2001-09-26 21:31:51 +0000754 if len(mro) > 2:
755 hr.maybe()
756 push('<dl><dt>Method resolution order:</dt>\n')
757 for base in mro:
758 push('<dd>%s</dd>\n' % self.classlink(base,
759 object.__module__))
760 push('</dl>\n')
761
Tim Petersb47879b2001-09-24 04:47:19 +0000762 def spill(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +0000763 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000764 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000765 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000766 push(msg)
767 for name, kind, homecls, value in ok:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100768 try:
769 value = getattr(object, name)
770 except Exception:
771 # Some descriptors may meet a failure in their __get__.
772 # (bug #1785)
773 push(self._docdescriptor(name, value, mod))
774 else:
775 push(self.document(value, name, mod,
776 funcs, classes, mdict, object))
Tim Petersb47879b2001-09-24 04:47:19 +0000777 push('\n')
778 return attrs
779
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000780 def spilldescriptors(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +0000781 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000782 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000783 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000784 push(msg)
785 for name, kind, homecls, value in ok:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000786 push(self._docdescriptor(name, value, mod))
Tim Petersb47879b2001-09-24 04:47:19 +0000787 return attrs
788
Tim Petersfa26f7c2001-09-24 08:05:11 +0000789 def spilldata(msg, attrs, predicate):
790 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000791 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000792 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000793 push(msg)
794 for name, kind, homecls, value in ok:
795 base = self.docother(getattr(object, name), name, mod)
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200796 if callable(value) or inspect.isdatadescriptor(value):
Guido van Rossum5e355b22002-05-21 20:56:15 +0000797 doc = getattr(value, "__doc__", None)
798 else:
799 doc = None
Tim Petersb47879b2001-09-24 04:47:19 +0000800 if doc is None:
801 push('<dl><dt>%s</dl>\n' % base)
802 else:
803 doc = self.markup(getdoc(value), self.preformat,
804 funcs, classes, mdict)
Tim Peters2306d242001-09-25 03:18:32 +0000805 doc = '<dd><tt>%s</tt>' % doc
Tim Petersb47879b2001-09-24 04:47:19 +0000806 push('<dl><dt>%s%s</dl>\n' % (base, doc))
807 push('\n')
808 return attrs
809
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000810 attrs = [(name, kind, cls, value)
811 for name, kind, cls, value in classify_class_attrs(object)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700812 if visiblename(name, obj=object)]
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000813
Tim Petersb47879b2001-09-24 04:47:19 +0000814 mdict = {}
815 for key, kind, homecls, value in attrs:
816 mdict[key] = anchor = '#' + name + '-' + key
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100817 try:
818 value = getattr(object, name)
819 except Exception:
820 # Some descriptors may meet a failure in their __get__.
821 # (bug #1785)
822 pass
Tim Petersb47879b2001-09-24 04:47:19 +0000823 try:
824 # The value may not be hashable (e.g., a data attr with
825 # a dict or list value).
826 mdict[value] = anchor
827 except TypeError:
828 pass
829
Tim Petersfa26f7c2001-09-24 08:05:11 +0000830 while attrs:
Tim Peters351e3622001-09-27 03:29:51 +0000831 if mro:
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000832 thisclass = mro.popleft()
Tim Peters351e3622001-09-27 03:29:51 +0000833 else:
834 thisclass = attrs[0][2]
Tim Petersfa26f7c2001-09-24 08:05:11 +0000835 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
836
Georg Brandl1a3284e2007-12-02 09:40:06 +0000837 if thisclass is builtins.object:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000838 attrs = inherited
839 continue
840 elif thisclass is object:
841 tag = 'defined here'
Tim Petersb47879b2001-09-24 04:47:19 +0000842 else:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000843 tag = 'inherited from %s' % self.classlink(thisclass,
844 object.__module__)
Tim Petersb47879b2001-09-24 04:47:19 +0000845 tag += ':<br>\n'
846
847 # Sort attrs by name.
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +0000848 attrs.sort(key=lambda t: t[0])
Tim Petersb47879b2001-09-24 04:47:19 +0000849
850 # Pump out the attrs, segregated by kind.
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000851 attrs = spill('Methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000852 lambda t: t[1] == 'method')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000853 attrs = spill('Class methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000854 lambda t: t[1] == 'class method')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000855 attrs = spill('Static methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000856 lambda t: t[1] == 'static method')
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000857 attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
858 lambda t: t[1] == 'data descriptor')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000859 attrs = spilldata('Data and other attributes %s' % tag, attrs,
Tim Petersfa26f7c2001-09-24 08:05:11 +0000860 lambda t: t[1] == 'data')
Tim Petersb47879b2001-09-24 04:47:19 +0000861 assert attrs == []
Tim Peters351e3622001-09-27 03:29:51 +0000862 attrs = inherited
Tim Petersb47879b2001-09-24 04:47:19 +0000863
864 contents = ''.join(contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000865
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000866 if name == realname:
867 title = '<a name="%s">class <strong>%s</strong></a>' % (
868 name, realname)
869 else:
870 title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
871 name, name, realname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000872 if bases:
873 parents = []
874 for base in bases:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000875 parents.append(self.classlink(base, object.__module__))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000876 title = title + '(%s)' % ', '.join(parents)
Tim Peters2306d242001-09-25 03:18:32 +0000877 doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000878 doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
Tim Petersc86f6ca2001-09-26 21:31:51 +0000879
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000880 return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000881
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000882 def formatvalue(self, object):
883 """Format an argument default value as text."""
Tim Peters2306d242001-09-25 03:18:32 +0000884 return self.grey('=' + self.repr(object))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000885
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000886 def docroutine(self, object, name=None, mod=None,
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000887 funcs={}, classes={}, methods={}, cl=None):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000888 """Produce HTML documentation for a function or method object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000889 realname = object.__name__
890 name = name or realname
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000891 anchor = (cl and cl.__name__ or '') + '-' + name
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000892 note = ''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000893 skipdocs = 0
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000894 if inspect.ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000895 imclass = object.__self__.__class__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000896 if cl:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000897 if imclass is not cl:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000898 note = ' from ' + self.classlink(imclass, mod)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000899 else:
Christian Heimesff737952007-11-27 10:40:20 +0000900 if object.__self__ is not None:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000901 note = ' method of %s instance' % self.classlink(
Christian Heimesff737952007-11-27 10:40:20 +0000902 object.__self__.__class__, mod)
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000903 else:
904 note = ' unbound %s method' % self.classlink(imclass,mod)
Christian Heimesff737952007-11-27 10:40:20 +0000905 object = object.__func__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000906
907 if name == realname:
908 title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
909 else:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000910 if (cl and realname in cl.__dict__ and
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000911 cl.__dict__[realname] is object):
Ka-Ping Yeee280c062001-03-23 14:05:53 +0000912 reallink = '<a href="#%s">%s</a>' % (
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000913 cl.__name__ + '-' + realname, realname)
914 skipdocs = 1
915 else:
916 reallink = realname
917 title = '<a name="%s"><strong>%s</strong></a> = %s' % (
918 anchor, name, reallink)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800919 argspec = None
920 if inspect.isfunction(object) or inspect.isbuiltin(object):
921 signature = inspect.signature(object)
922 if signature:
923 argspec = str(signature)
924 if realname == '<lambda>':
925 title = '<strong>%s</strong> <em>lambda</em> ' % name
926 # XXX lambda's won't usually have func_annotations['return']
927 # since the syntax doesn't support but it is possible.
928 # So removing parentheses isn't truly safe.
929 argspec = argspec[1:-1] # remove parentheses
930 if not argspec:
Tim Peters4bcfa312001-09-20 06:08:24 +0000931 argspec = '(...)'
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000932
Tim Peters2306d242001-09-25 03:18:32 +0000933 decl = title + argspec + (note and self.grey(
934 '<font face="helvetica, arial">%s</font>' % note))
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000935
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000936 if skipdocs:
Tim Peters2306d242001-09-25 03:18:32 +0000937 return '<dl><dt>%s</dt></dl>\n' % decl
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000938 else:
939 doc = self.markup(
940 getdoc(object), self.preformat, funcs, classes, methods)
Tim Peters2306d242001-09-25 03:18:32 +0000941 doc = doc and '<dd><tt>%s</tt></dd>' % doc
942 return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000943
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000944 def _docdescriptor(self, name, value, mod):
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000945 results = []
946 push = results.append
947
948 if name:
949 push('<dl><dt><strong>%s</strong></dt>\n' % name)
950 if value.__doc__ is not None:
Ka-Ping Yeebba6acc2005-02-19 22:58:26 +0000951 doc = self.markup(getdoc(value), self.preformat)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000952 push('<dd><tt>%s</tt></dd>\n' % doc)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000953 push('</dl>\n')
954
955 return ''.join(results)
956
957 def docproperty(self, object, name=None, mod=None, cl=None):
958 """Produce html documentation for a property."""
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000959 return self._docdescriptor(name, object, mod)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000960
Tim Peters8dd7ade2001-10-18 19:56:17 +0000961 def docother(self, object, name=None, mod=None, *ignored):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000962 """Produce HTML documentation for a data object."""
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000963 lhs = name and '<strong>%s</strong> = ' % name or ''
964 return lhs + self.repr(object)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000965
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000966 def docdata(self, object, name=None, mod=None, cl=None):
967 """Produce html documentation for a data descriptor."""
968 return self._docdescriptor(name, object, mod)
969
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000970 def index(self, dir, shadowed=None):
971 """Generate an HTML index for a directory of modules."""
972 modpkgs = []
973 if shadowed is None: shadowed = {}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000974 for importer, name, ispkg in pkgutil.iter_modules([dir]):
Victor Stinner4d652242011-04-12 23:41:50 +0200975 if any((0xD800 <= ord(ch) <= 0xDFFF) for ch in name):
976 # ignore a module if its name contains a surrogate character
977 continue
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000978 modpkgs.append((name, '', ispkg, name in shadowed))
979 shadowed[name] = 1
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000980
981 modpkgs.sort()
982 contents = self.multicolumn(modpkgs, self.modpkglink)
983 return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
984
985# -------------------------------------------- text documentation generator
986
987class TextRepr(Repr):
988 """Class for safely making a text representation of a Python object."""
989 def __init__(self):
990 Repr.__init__(self)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000991 self.maxlist = self.maxtuple = 20
992 self.maxdict = 10
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000993 self.maxstring = self.maxother = 100
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000994
995 def repr1(self, x, level):
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000996 if hasattr(type(x), '__name__'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000997 methodname = 'repr_' + '_'.join(type(x).__name__.split())
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000998 if hasattr(self, methodname):
999 return getattr(self, methodname)(x, level)
1000 return cram(stripid(repr(x)), self.maxother)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001001
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +00001002 def repr_string(self, x, level):
1003 test = cram(x, self.maxstring)
1004 testrepr = repr(test)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001005 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +00001006 # Backslashes are only literal in the string and are never
1007 # needed to make any special characters, so show a raw string.
1008 return 'r' + testrepr[0] + test + testrepr[0]
1009 return testrepr
1010
Skip Montanarodf708782002-03-07 22:58:02 +00001011 repr_str = repr_string
1012
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001013 def repr_instance(self, x, level):
1014 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001015 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001016 except:
1017 return '<%s instance>' % x.__class__.__name__
1018
1019class TextDoc(Doc):
1020 """Formatter class for text documentation."""
1021
1022 # ------------------------------------------- text formatting utilities
1023
1024 _repr_instance = TextRepr()
1025 repr = _repr_instance.repr
1026
1027 def bold(self, text):
1028 """Format a string in bold by overstriking."""
Georg Brandlcbd2ab12010-12-04 10:39:14 +00001029 return ''.join(ch + '\b' + ch for ch in text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001030
1031 def indent(self, text, prefix=' '):
1032 """Indent text by prepending a given prefix to each line."""
1033 if not text: return ''
Collin Winter72e110c2007-07-17 00:27:30 +00001034 lines = [prefix + line for line in text.split('\n')]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001035 if lines: lines[-1] = lines[-1].rstrip()
1036 return '\n'.join(lines)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001037
1038 def section(self, title, contents):
1039 """Format a section with a given heading."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001040 clean_contents = self.indent(contents).rstrip()
1041 return self.bold(title) + '\n' + clean_contents + '\n\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001042
1043 # ---------------------------------------------- type-specific routines
1044
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001045 def formattree(self, tree, modname, parent=None, prefix=''):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001046 """Render in text a class tree as returned by inspect.getclasstree()."""
1047 result = ''
1048 for entry in tree:
1049 if type(entry) is type(()):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001050 c, bases = entry
1051 result = result + prefix + classname(c, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001052 if bases and bases != (parent,):
Georg Brandlcbd2ab12010-12-04 10:39:14 +00001053 parents = (classname(c, modname) for c in bases)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001054 result = result + '(%s)' % ', '.join(parents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001055 result = result + '\n'
1056 elif type(entry) is type([]):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001057 result = result + self.formattree(
1058 entry, modname, c, prefix + ' ')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001059 return result
1060
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001061 def docmodule(self, object, name=None, mod=None):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001062 """Produce text documentation for a given module object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001063 name = object.__name__ # ignore the passed-in name
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001064 synop, desc = splitdoc(getdoc(object))
1065 result = self.section('NAME', name + (synop and ' - ' + synop))
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001066 all = getattr(object, '__all__', None)
Skip Montanaro4997a692003-09-10 16:47:51 +00001067 docloc = self.getdocloc(object)
1068 if docloc is not None:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001069 result = result + self.section('MODULE REFERENCE', docloc + """
1070
Éric Araujo647ef8c2011-09-11 00:43:20 +02001071The following documentation is automatically generated from the Python
1072source files. It may be incomplete, incorrect or include features that
1073are considered implementation detail and may vary between Python
1074implementations. When in doubt, consult the module reference at the
1075location listed above.
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001076""")
Skip Montanaro4997a692003-09-10 16:47:51 +00001077
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001078 if desc:
1079 result = result + self.section('DESCRIPTION', desc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001080
1081 classes = []
1082 for key, value in inspect.getmembers(object, inspect.isclass):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +00001083 # if __all__ exists, believe it. Otherwise use old heuristic.
1084 if (all is not None
1085 or (inspect.getmodule(value) or object) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001086 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001087 classes.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001088 funcs = []
1089 for key, value in inspect.getmembers(object, inspect.isroutine):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +00001090 # if __all__ exists, believe it. Otherwise use old heuristic.
1091 if (all is not None or
1092 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001093 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001094 funcs.append((key, value))
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001095 data = []
1096 for key, value in inspect.getmembers(object, isdata):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001097 if visiblename(key, all, object):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001098 data.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001099
Christian Heimes1af737c2008-01-23 08:24:23 +00001100 modpkgs = []
1101 modpkgs_names = set()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001102 if hasattr(object, '__path__'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
Christian Heimes1af737c2008-01-23 08:24:23 +00001104 modpkgs_names.add(modname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001105 if ispkg:
1106 modpkgs.append(modname + ' (package)')
1107 else:
1108 modpkgs.append(modname)
1109
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001110 modpkgs.sort()
1111 result = result + self.section(
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001112 'PACKAGE CONTENTS', '\n'.join(modpkgs))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001113
Christian Heimes1af737c2008-01-23 08:24:23 +00001114 # Detect submodules as sometimes created by C extensions
1115 submodules = []
1116 for key, value in inspect.getmembers(object, inspect.ismodule):
1117 if value.__name__.startswith(name + '.') and key not in modpkgs_names:
1118 submodules.append(key)
1119 if submodules:
1120 submodules.sort()
1121 result = result + self.section(
Amaury Forgeot d'Arc768db922008-04-24 21:00:04 +00001122 'SUBMODULES', '\n'.join(submodules))
Christian Heimes1af737c2008-01-23 08:24:23 +00001123
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001124 if classes:
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001125 classlist = [value for key, value in classes]
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001126 contents = [self.formattree(
1127 inspect.getclasstree(classlist, 1), name)]
1128 for key, value in classes:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001129 contents.append(self.document(value, key, name))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001130 result = result + self.section('CLASSES', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001131
1132 if funcs:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001133 contents = []
1134 for key, value in funcs:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001135 contents.append(self.document(value, key, name))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001136 result = result + self.section('FUNCTIONS', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001137
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001138 if data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001139 contents = []
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001140 for key, value in data:
Georg Brandl8b813db2005-10-01 16:32:31 +00001141 contents.append(self.docother(value, key, name, maxlen=70))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001142 result = result + self.section('DATA', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001143
1144 if hasattr(object, '__version__'):
1145 version = str(object.__version__)
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001146 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001147 version = version[11:-1].strip()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001148 result = result + self.section('VERSION', version)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +00001149 if hasattr(object, '__date__'):
1150 result = result + self.section('DATE', str(object.__date__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001151 if hasattr(object, '__author__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +00001152 result = result + self.section('AUTHOR', str(object.__author__))
1153 if hasattr(object, '__credits__'):
1154 result = result + self.section('CREDITS', str(object.__credits__))
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001155 try:
1156 file = inspect.getabsfile(object)
1157 except TypeError:
1158 file = '(built-in)'
1159 result = result + self.section('FILE', file)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001160 return result
1161
Georg Brandl9bd45f992010-12-03 09:58:38 +00001162 def docclass(self, object, name=None, mod=None, *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001163 """Produce text documentation for a given class object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001164 realname = object.__name__
1165 name = name or realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001166 bases = object.__bases__
1167
Tim Petersc86f6ca2001-09-26 21:31:51 +00001168 def makename(c, m=object.__module__):
1169 return classname(c, m)
1170
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001171 if name == realname:
1172 title = 'class ' + self.bold(realname)
1173 else:
1174 title = self.bold(name) + ' = class ' + realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001175 if bases:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001176 parents = map(makename, bases)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001177 title = title + '(%s)' % ', '.join(parents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001178
1179 doc = getdoc(object)
Tim Peters28355492001-09-23 21:29:55 +00001180 contents = doc and [doc + '\n'] or []
1181 push = contents.append
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001182
Tim Petersc86f6ca2001-09-26 21:31:51 +00001183 # List the mro, if non-trivial.
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001184 mro = deque(inspect.getmro(object))
Tim Petersc86f6ca2001-09-26 21:31:51 +00001185 if len(mro) > 2:
1186 push("Method resolution order:")
1187 for base in mro:
1188 push(' ' + makename(base))
1189 push('')
1190
Tim Petersf4aad8e2001-09-24 22:40:47 +00001191 # Cute little class to pump out a horizontal rule between sections.
1192 class HorizontalRule:
1193 def __init__(self):
1194 self.needone = 0
1195 def maybe(self):
1196 if self.needone:
1197 push('-' * 70)
1198 self.needone = 1
1199 hr = HorizontalRule()
1200
Tim Peters28355492001-09-23 21:29:55 +00001201 def spill(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +00001202 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001203 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001204 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001205 push(msg)
1206 for name, kind, homecls, value in ok:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +01001207 try:
1208 value = getattr(object, name)
1209 except Exception:
1210 # Some descriptors may meet a failure in their __get__.
1211 # (bug #1785)
1212 push(self._docdescriptor(name, value, mod))
1213 else:
1214 push(self.document(value,
1215 name, mod, object))
Tim Peters28355492001-09-23 21:29:55 +00001216 return attrs
1217
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001218 def spilldescriptors(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +00001219 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001220 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001221 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001222 push(msg)
1223 for name, kind, homecls, value in ok:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001224 push(self._docdescriptor(name, value, mod))
Tim Peters28355492001-09-23 21:29:55 +00001225 return attrs
Tim Petersb47879b2001-09-24 04:47:19 +00001226
Tim Petersfa26f7c2001-09-24 08:05:11 +00001227 def spilldata(msg, attrs, predicate):
1228 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001229 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001230 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001231 push(msg)
1232 for name, kind, homecls, value in ok:
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001233 if callable(value) or inspect.isdatadescriptor(value):
Ka-Ping Yeebba6acc2005-02-19 22:58:26 +00001234 doc = getdoc(value)
Guido van Rossum5e355b22002-05-21 20:56:15 +00001235 else:
1236 doc = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001237 push(self.docother(
1238 getattr(object, name, None) or homecls.__dict__[name],
1239 name, mod, maxlen=70, doc=doc) + '\n')
Tim Peters28355492001-09-23 21:29:55 +00001240 return attrs
1241
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001242 attrs = [(name, kind, cls, value)
1243 for name, kind, cls, value in classify_class_attrs(object)
Raymond Hettinger1103d052011-03-25 14:15:24 -07001244 if visiblename(name, obj=object)]
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001245
Tim Petersfa26f7c2001-09-24 08:05:11 +00001246 while attrs:
Tim Peters351e3622001-09-27 03:29:51 +00001247 if mro:
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001248 thisclass = mro.popleft()
Tim Peters351e3622001-09-27 03:29:51 +00001249 else:
1250 thisclass = attrs[0][2]
Tim Petersfa26f7c2001-09-24 08:05:11 +00001251 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
1252
Georg Brandl1a3284e2007-12-02 09:40:06 +00001253 if thisclass is builtins.object:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001254 attrs = inherited
1255 continue
1256 elif thisclass is object:
Tim Peters28355492001-09-23 21:29:55 +00001257 tag = "defined here"
1258 else:
Tim Petersfa26f7c2001-09-24 08:05:11 +00001259 tag = "inherited from %s" % classname(thisclass,
1260 object.__module__)
Tim Peters28355492001-09-23 21:29:55 +00001261 # Sort attrs by name.
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001262 attrs.sort()
Tim Peters28355492001-09-23 21:29:55 +00001263
1264 # Pump out the attrs, segregated by kind.
Tim Petersf4aad8e2001-09-24 22:40:47 +00001265 attrs = spill("Methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001266 lambda t: t[1] == 'method')
Tim Petersf4aad8e2001-09-24 22:40:47 +00001267 attrs = spill("Class methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001268 lambda t: t[1] == 'class method')
Tim Petersf4aad8e2001-09-24 22:40:47 +00001269 attrs = spill("Static methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001270 lambda t: t[1] == 'static method')
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001271 attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
1272 lambda t: t[1] == 'data descriptor')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001273 attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
1274 lambda t: t[1] == 'data')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001275
Tim Peters28355492001-09-23 21:29:55 +00001276 assert attrs == []
Tim Peters351e3622001-09-27 03:29:51 +00001277 attrs = inherited
Tim Peters28355492001-09-23 21:29:55 +00001278
1279 contents = '\n'.join(contents)
1280 if not contents:
1281 return title + '\n'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001282 return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001283
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001284 def formatvalue(self, object):
1285 """Format an argument default value as text."""
1286 return '=' + self.repr(object)
1287
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001288 def docroutine(self, object, name=None, mod=None, cl=None):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001289 """Produce text documentation for a function or method object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001290 realname = object.__name__
1291 name = name or realname
1292 note = ''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001293 skipdocs = 0
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001294 if inspect.ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +00001295 imclass = object.__self__.__class__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001296 if cl:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001297 if imclass is not cl:
1298 note = ' from ' + classname(imclass, mod)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001299 else:
Christian Heimesff737952007-11-27 10:40:20 +00001300 if object.__self__ is not None:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +00001301 note = ' method of %s instance' % classname(
Christian Heimesff737952007-11-27 10:40:20 +00001302 object.__self__.__class__, mod)
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +00001303 else:
1304 note = ' unbound %s method' % classname(imclass,mod)
Christian Heimesff737952007-11-27 10:40:20 +00001305 object = object.__func__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001306
1307 if name == realname:
1308 title = self.bold(realname)
1309 else:
Raymond Hettinger54f02222002-06-01 14:18:47 +00001310 if (cl and realname in cl.__dict__ and
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001311 cl.__dict__[realname] is object):
1312 skipdocs = 1
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001313 title = self.bold(name) + ' = ' + realname
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001314 argspec = None
1315 if inspect.isfunction(object) or inspect.isbuiltin(object):
1316 signature = inspect.signature(object)
1317 if signature:
1318 argspec = str(signature)
1319 if realname == '<lambda>':
1320 title = self.bold(name) + ' lambda '
1321 # XXX lambda's won't usually have func_annotations['return']
1322 # since the syntax doesn't support but it is possible.
1323 # So removing parentheses isn't truly safe.
1324 argspec = argspec[1:-1] # remove parentheses
1325 if not argspec:
Tim Peters4bcfa312001-09-20 06:08:24 +00001326 argspec = '(...)'
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001327 decl = title + argspec + note
1328
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001329 if skipdocs:
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001330 return decl + '\n'
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001331 else:
1332 doc = getdoc(object) or ''
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001333 return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001334
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001335 def _docdescriptor(self, name, value, mod):
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001336 results = []
1337 push = results.append
1338
1339 if name:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001340 push(self.bold(name))
1341 push('\n')
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001342 doc = getdoc(value) or ''
1343 if doc:
1344 push(self.indent(doc))
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001345 push('\n')
1346 return ''.join(results)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001347
1348 def docproperty(self, object, name=None, mod=None, cl=None):
1349 """Produce text documentation for a property."""
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001350 return self._docdescriptor(name, object, mod)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001351
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001352 def docdata(self, object, name=None, mod=None, cl=None):
1353 """Produce text documentation for a data descriptor."""
1354 return self._docdescriptor(name, object, mod)
1355
Georg Brandl8b813db2005-10-01 16:32:31 +00001356 def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001357 """Produce text documentation for a data object."""
1358 repr = self.repr(object)
1359 if maxlen:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001360 line = (name and name + ' = ' or '') + repr
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001361 chop = maxlen - len(line)
1362 if chop < 0: repr = repr[:chop] + '...'
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001363 line = (name and self.bold(name) + ' = ' or '') + repr
Tim Peters28355492001-09-23 21:29:55 +00001364 if doc is not None:
1365 line += '\n' + self.indent(str(doc))
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001366 return line
1367
Georg Brandld80d5f42010-12-03 07:47:22 +00001368class _PlainTextDoc(TextDoc):
1369 """Subclass of TextDoc which overrides string styling"""
1370 def bold(self, text):
1371 return text
1372
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001373# --------------------------------------------------------- user interfaces
1374
1375def pager(text):
1376 """The first time this is called, determine what kind of pager to use."""
1377 global pager
1378 pager = getpager()
1379 pager(text)
1380
1381def getpager():
1382 """Decide what method to use for paging through text."""
Guido van Rossuma01a8b62007-05-27 09:20:14 +00001383 if not hasattr(sys.stdout, "isatty"):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001384 return plainpager
1385 if not sys.stdin.isatty() or not sys.stdout.isatty():
1386 return plainpager
Raymond Hettinger54f02222002-06-01 14:18:47 +00001387 if 'PAGER' in os.environ:
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001388 if sys.platform == 'win32': # pipes completely broken in Windows
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001389 return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001390 elif os.environ.get('TERM') in ('dumb', 'emacs'):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001391 return lambda text: pipepager(plain(text), os.environ['PAGER'])
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001392 else:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001393 return lambda text: pipepager(text, os.environ['PAGER'])
Ka-Ping Yeea487e4e2005-11-05 04:49:18 +00001394 if os.environ.get('TERM') in ('dumb', 'emacs'):
1395 return plainpager
Jesus Cea4791a242012-10-05 03:15:39 +02001396 if sys.platform == 'win32':
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001397 return lambda text: tempfilepager(plain(text), 'more <')
Skip Montanarod404bee2002-09-26 21:44:57 +00001398 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001399 return lambda text: pipepager(text, 'less')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001400
1401 import tempfile
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001402 (fd, filename) = tempfile.mkstemp()
1403 os.close(fd)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001404 try:
Georg Brandl3dbca812008-07-23 16:10:53 +00001405 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001406 return lambda text: pipepager(text, 'more')
1407 else:
1408 return ttypager
1409 finally:
1410 os.unlink(filename)
1411
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001412def plain(text):
1413 """Remove boldface formatting from text."""
1414 return re.sub('.\b', '', text)
1415
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001416def pipepager(text, cmd):
1417 """Page through text by feeding it to another program."""
1418 pipe = os.popen(cmd, 'w')
1419 try:
1420 pipe.write(text)
1421 pipe.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001422 except OSError:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001423 pass # Ignore broken pipes caused by quitting the pager program.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001424
1425def tempfilepager(text, cmd):
1426 """Page through text by invoking a program on a temporary file."""
1427 import tempfile
Tim Peters550e4e52003-02-07 01:53:46 +00001428 filename = tempfile.mktemp()
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01001429 with open(filename, 'w') as file:
1430 file.write(text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001431 try:
Georg Brandl3dbca812008-07-23 16:10:53 +00001432 os.system(cmd + ' "' + filename + '"')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001433 finally:
1434 os.unlink(filename)
1435
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001436def ttypager(text):
1437 """Page through text on a text terminal."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001438 lines = plain(text).split('\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001439 try:
1440 import tty
1441 fd = sys.stdin.fileno()
1442 old = tty.tcgetattr(fd)
1443 tty.setcbreak(fd)
1444 getchar = lambda: sys.stdin.read(1)
Ka-Ping Yee457aab22001-02-27 23:36:29 +00001445 except (ImportError, AttributeError):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001446 tty = None
1447 getchar = lambda: sys.stdin.readline()[:-1][:1]
1448
1449 try:
1450 r = inc = os.environ.get('LINES', 25) - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001451 sys.stdout.write('\n'.join(lines[:inc]) + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001452 while lines[r:]:
1453 sys.stdout.write('-- more --')
1454 sys.stdout.flush()
1455 c = getchar()
1456
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001457 if c in ('q', 'Q'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001458 sys.stdout.write('\r \r')
1459 break
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001460 elif c in ('\r', '\n'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001461 sys.stdout.write('\r \r' + lines[r] + '\n')
1462 r = r + 1
1463 continue
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001464 if c in ('b', 'B', '\x1b'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001465 r = r - inc - inc
1466 if r < 0: r = 0
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001467 sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001468 r = r + inc
1469
1470 finally:
1471 if tty:
1472 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
1473
1474def plainpager(text):
1475 """Simply print unformatted text. This is the ultimate fallback."""
1476 sys.stdout.write(plain(text))
1477
1478def describe(thing):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001479 """Produce a short description of the given thing."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001480 if inspect.ismodule(thing):
1481 if thing.__name__ in sys.builtin_module_names:
1482 return 'built-in module ' + thing.__name__
1483 if hasattr(thing, '__path__'):
1484 return 'package ' + thing.__name__
1485 else:
1486 return 'module ' + thing.__name__
1487 if inspect.isbuiltin(thing):
1488 return 'built-in function ' + thing.__name__
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489 if inspect.isgetsetdescriptor(thing):
1490 return 'getset descriptor %s.%s.%s' % (
1491 thing.__objclass__.__module__, thing.__objclass__.__name__,
1492 thing.__name__)
1493 if inspect.ismemberdescriptor(thing):
1494 return 'member descriptor %s.%s.%s' % (
1495 thing.__objclass__.__module__, thing.__objclass__.__name__,
1496 thing.__name__)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001497 if inspect.isclass(thing):
1498 return 'class ' + thing.__name__
1499 if inspect.isfunction(thing):
1500 return 'function ' + thing.__name__
1501 if inspect.ismethod(thing):
1502 return 'method ' + thing.__name__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001503 return type(thing).__name__
1504
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001505def locate(path, forceload=0):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001506 """Locate an object by name or dotted path, importing as necessary."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001507 parts = [part for part in path.split('.') if part]
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001508 module, n = None, 0
1509 while n < len(parts):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001510 nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001511 if nextmodule: module, n = nextmodule, n + 1
1512 else: break
1513 if module:
1514 object = module
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001515 else:
Éric Araujoe64e51b2011-07-29 17:03:55 +02001516 object = builtins
1517 for part in parts[n:]:
1518 try:
1519 object = getattr(object, part)
1520 except AttributeError:
1521 return None
1522 return object
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001523
1524# --------------------------------------- interactive interpreter interface
1525
1526text = TextDoc()
Georg Brandld80d5f42010-12-03 07:47:22 +00001527plaintext = _PlainTextDoc()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001528html = HTMLDoc()
1529
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001530def resolve(thing, forceload=0):
1531 """Given an object or a path to an object, get the object and its name."""
1532 if isinstance(thing, str):
1533 object = locate(thing, forceload)
1534 if not object:
Collin Winterce36ad82007-08-30 01:19:48 +00001535 raise ImportError('no Python documentation found for %r' % thing)
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001536 return object, thing
1537 else:
R David Murrayc43125a2012-04-23 13:23:57 -04001538 name = getattr(thing, '__name__', None)
1539 return thing, name if isinstance(name, str) else None
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001540
Georg Brandld80d5f42010-12-03 07:47:22 +00001541def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
1542 renderer=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001543 """Render text documentation, given an object or a path to an object."""
Georg Brandld80d5f42010-12-03 07:47:22 +00001544 if renderer is None:
1545 renderer = text
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546 object, name = resolve(thing, forceload)
1547 desc = describe(object)
1548 module = inspect.getmodule(object)
1549 if name and '.' in name:
1550 desc += ' in ' + name[:name.rfind('.')]
1551 elif module and module is not object:
1552 desc += ' in module ' + module.__name__
Amaury Forgeot d'Arc768db922008-04-24 21:00:04 +00001553
1554 if not (inspect.ismodule(object) or
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555 inspect.isclass(object) or
1556 inspect.isroutine(object) or
1557 inspect.isgetsetdescriptor(object) or
1558 inspect.ismemberdescriptor(object) or
1559 isinstance(object, property)):
1560 # If the passed object is a piece of data or an instance,
1561 # document its available methods instead of its value.
1562 object = type(object)
1563 desc += ' object'
Georg Brandld80d5f42010-12-03 07:47:22 +00001564 return title % desc + '\n\n' + renderer.document(object, name)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001565
Georg Brandld80d5f42010-12-03 07:47:22 +00001566def doc(thing, title='Python Library Documentation: %s', forceload=0,
1567 output=None):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001568 """Display text documentation, given an object or a path to an object."""
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001569 try:
Georg Brandld80d5f42010-12-03 07:47:22 +00001570 if output is None:
1571 pager(render_doc(thing, title, forceload))
1572 else:
1573 output.write(render_doc(thing, title, forceload, plaintext))
Guido van Rossumb940e112007-01-10 16:19:56 +00001574 except (ImportError, ErrorDuringImport) as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001575 print(value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001576
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001577def writedoc(thing, forceload=0):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001578 """Write HTML documentation to a file in the current directory."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001579 try:
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001580 object, name = resolve(thing, forceload)
1581 page = html.page(describe(object), html.document(object, name))
Georg Brandl388faac2009-04-10 08:31:48 +00001582 file = open(name + '.html', 'w', encoding='utf-8')
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001583 file.write(page)
1584 file.close()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001585 print('wrote', name + '.html')
Guido van Rossumb940e112007-01-10 16:19:56 +00001586 except (ImportError, ErrorDuringImport) as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001587 print(value)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001588
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001589def writedocs(dir, pkgpath='', done=None):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001590 """Write out HTML documentation for all modules in a directory tree."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001591 if done is None: done = {}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001592 for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
1593 writedoc(modname)
1594 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001595
1596class Helper:
Georg Brandl6b38daa2008-06-01 21:05:17 +00001597
1598 # These dictionaries map a topic name to either an alias, or a tuple
1599 # (label, seealso-items). The "label" is the label of the corresponding
1600 # section in the .rst file under Doc/ and an index into the dictionary
Georg Brandl5617db82009-04-27 16:28:57 +00001601 # in pydoc_data/topics.py.
Georg Brandl6b38daa2008-06-01 21:05:17 +00001602 #
1603 # CAUTION: if you change one of these dictionaries, be sure to adapt the
1604 # list of needed labels in Doc/tools/sphinxext/pyspecific.py and
Georg Brandl5617db82009-04-27 16:28:57 +00001605 # regenerate the pydoc_data/topics.py file by running
Georg Brandl6b38daa2008-06-01 21:05:17 +00001606 # make pydoc-topics
1607 # in Doc/ and copying the output file into the Lib/ directory.
1608
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001609 keywords = {
Ezio Melottib185a042011-04-28 07:42:55 +03001610 'False': '',
1611 'None': '',
1612 'True': '',
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001613 'and': 'BOOLEAN',
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614 'as': 'with',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001615 'assert': ('assert', ''),
1616 'break': ('break', 'while for'),
1617 'class': ('class', 'CLASSES SPECIALMETHODS'),
1618 'continue': ('continue', 'while for'),
1619 'def': ('function', ''),
1620 'del': ('del', 'BASICMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001621 'elif': 'if',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001622 'else': ('else', 'while for'),
Georg Brandl0d855392008-08-30 19:53:05 +00001623 'except': 'try',
1624 'finally': 'try',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001625 'for': ('for', 'break continue while'),
Georg Brandl0d855392008-08-30 19:53:05 +00001626 'from': 'import',
Georg Brandl74abf6f2010-11-20 19:54:36 +00001627 'global': ('global', 'nonlocal NAMESPACES'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001628 'if': ('if', 'TRUTHVALUE'),
1629 'import': ('import', 'MODULES'),
Georg Brandl395ed242009-09-04 08:07:32 +00001630 'in': ('in', 'SEQUENCEMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001631 'is': 'COMPARISON',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001632 'lambda': ('lambda', 'FUNCTIONS'),
Georg Brandl74abf6f2010-11-20 19:54:36 +00001633 'nonlocal': ('nonlocal', 'global NAMESPACES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001634 'not': 'BOOLEAN',
1635 'or': 'BOOLEAN',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001636 'pass': ('pass', ''),
1637 'raise': ('raise', 'EXCEPTIONS'),
1638 'return': ('return', 'FUNCTIONS'),
1639 'try': ('try', 'EXCEPTIONS'),
1640 'while': ('while', 'break continue if TRUTHVALUE'),
1641 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
1642 'yield': ('yield', ''),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001643 }
Georg Brandldb7b6b92009-01-01 15:53:14 +00001644 # Either add symbols to this dictionary or to the symbols dictionary
1645 # directly: Whichever is easier. They are merged later.
1646 _symbols_inverse = {
1647 'STRINGS' : ("'", "'''", "r'", "b'", '"""', '"', 'r"', 'b"'),
1648 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
1649 '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
1650 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
1651 'UNARY' : ('-', '~'),
1652 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
1653 '^=', '<<=', '>>=', '**=', '//='),
1654 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
1655 'COMPLEX' : ('j', 'J')
1656 }
1657 symbols = {
1658 '%': 'OPERATORS FORMATTING',
1659 '**': 'POWER',
1660 ',': 'TUPLES LISTS FUNCTIONS',
1661 '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
1662 '...': 'ELLIPSIS',
1663 ':': 'SLICINGS DICTIONARYLITERALS',
1664 '@': 'def class',
1665 '\\': 'STRINGS',
1666 '_': 'PRIVATENAMES',
1667 '__': 'PRIVATENAMES SPECIALMETHODS',
1668 '`': 'BACKQUOTES',
1669 '(': 'TUPLES FUNCTIONS CALLS',
1670 ')': 'TUPLES FUNCTIONS CALLS',
1671 '[': 'LISTS SUBSCRIPTS SLICINGS',
1672 ']': 'LISTS SUBSCRIPTS SLICINGS'
1673 }
1674 for topic, symbols_ in _symbols_inverse.items():
1675 for symbol in symbols_:
1676 topics = symbols.get(symbol, topic)
1677 if topic not in topics:
1678 topics = topics + ' ' + topic
1679 symbols[symbol] = topics
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001680
1681 topics = {
Georg Brandl6b38daa2008-06-01 21:05:17 +00001682 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
1683 'FUNCTIONS CLASSES MODULES FILES inspect'),
1684 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS '
1685 'FORMATTING TYPES'),
1686 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
1687 'FORMATTING': ('formatstrings', 'OPERATORS'),
1688 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
1689 'FORMATTING TYPES'),
1690 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
1691 'INTEGER': ('integers', 'int range'),
1692 'FLOAT': ('floating', 'float math'),
1693 'COMPLEX': ('imaginary', 'complex cmath'),
1694 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001695 'MAPPINGS': 'DICTIONARIES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001696 'FUNCTIONS': ('typesfunctions', 'def TYPES'),
1697 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
1698 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
1699 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001700 'FRAMEOBJECTS': 'TYPES',
1701 'TRACEBACKS': 'TYPES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001702 'NONE': ('bltin-null-object', ''),
1703 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
1704 'FILES': ('bltin-file-objects', ''),
1705 'SPECIALATTRIBUTES': ('specialattrs', ''),
1706 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
1707 'MODULES': ('typesmodules', 'import'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001708 'PACKAGES': 'import',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001709 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
1710 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
1711 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
1712 'LISTS DICTIONARIES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001713 'OPERATORS': 'EXPRESSIONS',
1714 'PRECEDENCE': 'EXPRESSIONS',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001715 'OBJECTS': ('objects', 'TYPES'),
1716 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
Georg Brandl395ed242009-09-04 08:07:32 +00001717 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '
1718 'NUMBERMETHODS CLASSES'),
Mark Dickinsona56c4672009-01-27 18:17:45 +00001719 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001720 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
1721 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
Georg Brandl395ed242009-09-04 08:07:32 +00001722 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS '
Georg Brandl6b38daa2008-06-01 21:05:17 +00001723 'SPECIALMETHODS'),
1724 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
1725 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
1726 'SPECIALMETHODS'),
1727 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
Georg Brandl74abf6f2010-11-20 19:54:36 +00001728 'NAMESPACES': ('naming', 'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001729 'DYNAMICFEATURES': ('dynamic-features', ''),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001730 'SCOPING': 'NAMESPACES',
1731 'FRAMES': 'NAMESPACES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001732 'EXCEPTIONS': ('exceptions', 'try except finally raise'),
1733 'CONVERSIONS': ('conversions', ''),
1734 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
1735 'SPECIALIDENTIFIERS': ('id-classes', ''),
1736 'PRIVATENAMES': ('atom-identifiers', ''),
1737 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS '
1738 'LISTLITERALS DICTIONARYLITERALS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001739 'TUPLES': 'SEQUENCES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001740 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
1741 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
1742 'LISTLITERALS': ('lists', 'LISTS LITERALS'),
1743 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
1744 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
1745 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
Georg Brandl395ed242009-09-04 08:07:32 +00001746 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'),
1747 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001748 'CALLS': ('calls', 'EXPRESSIONS'),
1749 'POWER': ('power', 'EXPRESSIONS'),
1750 'UNARY': ('unary', 'EXPRESSIONS'),
1751 'BINARY': ('binary', 'EXPRESSIONS'),
1752 'SHIFTING': ('shifting', 'EXPRESSIONS'),
1753 'BITWISE': ('bitwise', 'EXPRESSIONS'),
1754 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
1755 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001756 'ASSERTION': 'assert',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001757 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
1758 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001759 'DELETION': 'del',
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001760 'RETURNING': 'return',
1761 'IMPORTING': 'import',
1762 'CONDITIONAL': 'if',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001763 'LOOPING': ('compound', 'for while break continue'),
1764 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
1765 'DEBUGGING': ('debugger', 'pdb'),
1766 'CONTEXTMANAGERS': ('context-managers', 'with'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001767 }
1768
Georg Brandl78aa3962010-07-31 21:51:48 +00001769 def __init__(self, input=None, output=None):
1770 self._input = input
1771 self._output = output
1772
Georg Brandl76ae3972010-08-01 06:32:55 +00001773 input = property(lambda self: self._input or sys.stdin)
1774 output = property(lambda self: self._output or sys.stdout)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001775
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001776 def __repr__(self):
Ka-Ping Yee9bc576b2001-04-13 13:57:31 +00001777 if inspect.stack()[1][3] == '?':
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001778 self()
1779 return ''
Ka-Ping Yee9bc576b2001-04-13 13:57:31 +00001780 return '<pydoc.Helper instance>'
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001781
Alexander Belopolsky2e733c92010-07-04 17:00:20 +00001782 _GoInteractive = object()
1783 def __call__(self, request=_GoInteractive):
1784 if request is not self._GoInteractive:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001785 self.help(request)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001786 else:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001787 self.intro()
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001788 self.interact()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001789 self.output.write('''
Fred Drakee61967f2001-05-10 18:41:02 +00001790You are now leaving help and returning to the Python interpreter.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001791If you want to ask for help on a particular object directly from the
1792interpreter, you can type "help(object)". Executing "help('string')"
1793has the same effect as typing a particular string at the help> prompt.
1794''')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001795
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001796 def interact(self):
1797 self.output.write('\n')
Guido van Rossum8ca162f2002-04-07 06:36:23 +00001798 while True:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001799 try:
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001800 request = self.getline('help> ')
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001801 if not request: break
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001802 except (KeyboardInterrupt, EOFError):
1803 break
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001804 request = replace(request, '"', '', "'", '').strip()
1805 if request.lower() in ('q', 'quit'): break
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001806 self.help(request)
1807
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001808 def getline(self, prompt):
Guido van Rossum7c086c02008-01-02 03:52:38 +00001809 """Read one line, using input() when appropriate."""
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001810 if self.input is sys.stdin:
Guido van Rossum7c086c02008-01-02 03:52:38 +00001811 return input(prompt)
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001812 else:
1813 self.output.write(prompt)
1814 self.output.flush()
1815 return self.input.readline()
1816
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001817 def help(self, request):
1818 if type(request) is type(''):
R. David Murray1f1b9d32009-05-27 20:56:59 +00001819 request = request.strip()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001820 if request == 'help': self.intro()
1821 elif request == 'keywords': self.listkeywords()
Georg Brandldb7b6b92009-01-01 15:53:14 +00001822 elif request == 'symbols': self.listsymbols()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001823 elif request == 'topics': self.listtopics()
1824 elif request == 'modules': self.listmodules()
1825 elif request[:8] == 'modules ':
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001826 self.listmodules(request.split()[1])
Georg Brandldb7b6b92009-01-01 15:53:14 +00001827 elif request in self.symbols: self.showsymbol(request)
Ezio Melottib185a042011-04-28 07:42:55 +03001828 elif request in ['True', 'False', 'None']:
1829 # special case these keywords since they are objects too
1830 doc(eval(request), 'Help on %s:')
Raymond Hettinger54f02222002-06-01 14:18:47 +00001831 elif request in self.keywords: self.showtopic(request)
1832 elif request in self.topics: self.showtopic(request)
Georg Brandld80d5f42010-12-03 07:47:22 +00001833 elif request: doc(request, 'Help on %s:', output=self._output)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001834 elif isinstance(request, Helper): self()
Georg Brandld80d5f42010-12-03 07:47:22 +00001835 else: doc(request, 'Help on %s:', output=self._output)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001836 self.output.write('\n')
1837
1838 def intro(self):
1839 self.output.write('''
Georg Brandlc645c6a2012-06-24 17:24:26 +02001840Welcome to Python %s! This is the interactive help utility.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001841
1842If this is your first time using Python, you should definitely check out
R David Murrayde0f6292012-03-31 12:06:35 -04001843the tutorial on the Internet at http://docs.python.org/%s/tutorial/.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001844
1845Enter the name of any module, keyword, or topic to get help on writing
1846Python programs and using Python modules. To quit this help utility and
1847return to the interpreter, just type "quit".
1848
Terry Jan Reedy34200572013-02-11 02:23:13 -05001849To get a list of available modules, keywords, symbols, or topics, type
1850"modules", "keywords", "symbols", or "topics". Each module also comes
1851with a one-line summary of what it does; to list the modules whose name
1852or summary contain a given string such as "spam", type "modules spam".
R David Murrayde0f6292012-03-31 12:06:35 -04001853''' % tuple([sys.version[:3]]*2))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001854
1855 def list(self, items, columns=4, width=80):
Guido van Rossum486364b2007-06-30 05:01:58 +00001856 items = list(sorted(items))
1857 colw = width // columns
1858 rows = (len(items) + columns - 1) // columns
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001859 for row in range(rows):
1860 for col in range(columns):
1861 i = col * rows + row
1862 if i < len(items):
1863 self.output.write(items[i])
1864 if col < columns - 1:
Guido van Rossum486364b2007-06-30 05:01:58 +00001865 self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001866 self.output.write('\n')
1867
1868 def listkeywords(self):
1869 self.output.write('''
1870Here is a list of the Python keywords. Enter any keyword to get more help.
1871
1872''')
1873 self.list(self.keywords.keys())
1874
Georg Brandldb7b6b92009-01-01 15:53:14 +00001875 def listsymbols(self):
1876 self.output.write('''
1877Here is a list of the punctuation symbols which Python assigns special meaning
1878to. Enter any symbol to get more help.
1879
1880''')
1881 self.list(self.symbols.keys())
1882
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001883 def listtopics(self):
1884 self.output.write('''
1885Here is a list of available topics. Enter any topic name to get more help.
1886
1887''')
1888 self.list(self.topics.keys())
1889
Georg Brandldb7b6b92009-01-01 15:53:14 +00001890 def showtopic(self, topic, more_xrefs=''):
Georg Brandl6b38daa2008-06-01 21:05:17 +00001891 try:
Georg Brandl5617db82009-04-27 16:28:57 +00001892 import pydoc_data.topics
Brett Cannoncd171c82013-07-04 17:43:24 -04001893 except ImportError:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001894 self.output.write('''
Georg Brandl6b38daa2008-06-01 21:05:17 +00001895Sorry, topic and keyword documentation is not available because the
Georg Brandl5617db82009-04-27 16:28:57 +00001896module "pydoc_data.topics" could not be found.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001897''')
1898 return
1899 target = self.topics.get(topic, self.keywords.get(topic))
1900 if not target:
1901 self.output.write('no documentation found for %s\n' % repr(topic))
1902 return
1903 if type(target) is type(''):
Georg Brandldb7b6b92009-01-01 15:53:14 +00001904 return self.showtopic(target, more_xrefs)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001905
Georg Brandl6b38daa2008-06-01 21:05:17 +00001906 label, xrefs = target
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001907 try:
Georg Brandl5617db82009-04-27 16:28:57 +00001908 doc = pydoc_data.topics.topics[label]
Georg Brandl6b38daa2008-06-01 21:05:17 +00001909 except KeyError:
1910 self.output.write('no documentation found for %s\n' % repr(topic))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001911 return
Georg Brandl6b38daa2008-06-01 21:05:17 +00001912 pager(doc.strip() + '\n')
Georg Brandldb7b6b92009-01-01 15:53:14 +00001913 if more_xrefs:
1914 xrefs = (xrefs or '') + ' ' + more_xrefs
Ka-Ping Yeeda793892001-04-13 11:02:51 +00001915 if xrefs:
Brett Cannon1448ecf2013-10-04 11:38:59 -04001916 import textwrap
1917 text = 'Related help topics: ' + ', '.join(xrefs.split()) + '\n'
1918 wrapped_text = textwrap.wrap(text, 72)
1919 self.output.write('\n%s\n' % ''.join(wrapped_text))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001920
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001921 def _gettopic(self, topic, more_xrefs=''):
1922 """Return unbuffered tuple of (topic, xrefs).
1923
Georg Brandld2f38572011-01-30 08:37:19 +00001924 If an error occurs here, the exception is caught and displayed by
1925 the url handler.
1926
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001927 This function duplicates the showtopic method but returns its
1928 result directly so it can be formatted for display in an html page.
1929 """
1930 try:
1931 import pydoc_data.topics
Brett Cannoncd171c82013-07-04 17:43:24 -04001932 except ImportError:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001933 return('''
1934Sorry, topic and keyword documentation is not available because the
1935module "pydoc_data.topics" could not be found.
1936''' , '')
1937 target = self.topics.get(topic, self.keywords.get(topic))
1938 if not target:
Georg Brandld2f38572011-01-30 08:37:19 +00001939 raise ValueError('could not find topic')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001940 if isinstance(target, str):
1941 return self._gettopic(target, more_xrefs)
1942 label, xrefs = target
Georg Brandld2f38572011-01-30 08:37:19 +00001943 doc = pydoc_data.topics.topics[label]
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001944 if more_xrefs:
1945 xrefs = (xrefs or '') + ' ' + more_xrefs
1946 return doc, xrefs
1947
Georg Brandldb7b6b92009-01-01 15:53:14 +00001948 def showsymbol(self, symbol):
1949 target = self.symbols[symbol]
1950 topic, _, xrefs = target.partition(' ')
1951 self.showtopic(topic, xrefs)
1952
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001953 def listmodules(self, key=''):
1954 if key:
1955 self.output.write('''
Terry Jan Reedy34200572013-02-11 02:23:13 -05001956Here is a list of modules whose name or summary contains '{}'.
1957If there are any, enter a module name to get more help.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001958
Terry Jan Reedy34200572013-02-11 02:23:13 -05001959'''.format(key))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001960 apropos(key)
1961 else:
1962 self.output.write('''
1963Please wait a moment while I gather a list of all available modules...
1964
1965''')
1966 modules = {}
1967 def callback(path, modname, desc, modules=modules):
1968 if modname and modname[-9:] == '.__init__':
1969 modname = modname[:-9] + ' (package)'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001970 if modname.find('.') < 0:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001971 modules[modname] = 1
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001972 def onerror(modname):
1973 callback(None, modname, None)
1974 ModuleScanner().run(callback, onerror=onerror)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001975 self.list(modules.keys())
1976 self.output.write('''
1977Enter any module name to get more help. Or, type "modules spam" to search
Terry Jan Reedy34200572013-02-11 02:23:13 -05001978for modules whose name or summary contain the string "spam".
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001979''')
1980
Georg Brandl78aa3962010-07-31 21:51:48 +00001981help = Helper()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001982
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001983class ModuleScanner:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001984 """An interruptible scanner that searches module synopses."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001985
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001986 def run(self, callback, key=None, completer=None, onerror=None):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001987 if key: key = key.lower()
Guido van Rossum8ca162f2002-04-07 06:36:23 +00001988 self.quit = False
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001989 seen = {}
1990
1991 for modname in sys.builtin_module_names:
Ka-Ping Yee239432a2001-03-02 02:45:08 +00001992 if modname != '__main__':
1993 seen[modname] = 1
Ka-Ping Yee66246962001-04-12 11:59:50 +00001994 if key is None:
1995 callback(None, modname, '')
1996 else:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001997 name = __import__(modname).__doc__ or ''
1998 desc = name.split('\n')[0]
1999 name = modname + ' - ' + desc
2000 if name.lower().find(key) >= 0:
Ka-Ping Yee66246962001-04-12 11:59:50 +00002001 callback(None, modname, desc)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002002
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002003 for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002004 if self.quit:
2005 break
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002007 if key is None:
2008 callback(None, modname, '')
2009 else:
Georg Brandl126c8792009-04-05 15:05:48 +00002010 try:
2011 loader = importer.find_module(modname)
2012 except SyntaxError:
2013 # raised by tests for bad coding cookies or BOM
2014 continue
2015 if hasattr(loader, 'get_source'):
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002016 try:
2017 source = loader.get_source(modname)
Nick Coghlan2824cb52012-07-15 22:12:14 +10002018 except Exception:
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002019 if onerror:
2020 onerror(modname)
2021 continue
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002022 desc = source_synopsis(io.StringIO(source)) or ''
Georg Brandl126c8792009-04-05 15:05:48 +00002023 if hasattr(loader, 'get_filename'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002024 path = loader.get_filename(modname)
Ka-Ping Yee66246962001-04-12 11:59:50 +00002025 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002026 path = None
2027 else:
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002028 try:
2029 module = loader.load_module(modname)
2030 except ImportError:
2031 if onerror:
2032 onerror(modname)
2033 continue
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002034 desc = (module.__doc__ or '').splitlines()[0]
2035 path = getattr(module,'__file__',None)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002036 name = modname + ' - ' + desc
2037 if name.lower().find(key) >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002038 callback(path, modname, desc)
2039
2040 if completer:
2041 completer()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002042
2043def apropos(key):
2044 """Print all the one-line module summaries that contain a substring."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002045 def callback(path, modname, desc):
2046 if modname[-9:] == '.__init__':
2047 modname = modname[:-9] + ' (package)'
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002048 print(modname, desc and '- ' + desc)
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002049 def onerror(modname):
2050 pass
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002051 with warnings.catch_warnings():
2052 warnings.filterwarnings('ignore') # ignore problems during import
2053 ModuleScanner().run(callback, key, onerror=onerror)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002054
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002055# --------------------------------------- enhanced Web browser interface
2056
2057def _start_server(urlhandler, port):
2058 """Start an HTTP server thread on a specific port.
2059
2060 Start an HTML/text server thread, so HTML or text documents can be
2061 browsed dynamically and interactively with a Web browser. Example use:
2062
2063 >>> import time
2064 >>> import pydoc
2065
2066 Define a URL handler. To determine what the client is asking
2067 for, check the URL and content_type.
2068
2069 Then get or generate some text or HTML code and return it.
2070
2071 >>> def my_url_handler(url, content_type):
2072 ... text = 'the URL sent was: (%s, %s)' % (url, content_type)
2073 ... return text
2074
2075 Start server thread on port 0.
2076 If you use port 0, the server will pick a random port number.
2077 You can then use serverthread.port to get the port number.
2078
2079 >>> port = 0
2080 >>> serverthread = pydoc._start_server(my_url_handler, port)
2081
2082 Check that the server is really started. If it is, open browser
2083 and get first page. Use serverthread.url as the starting page.
2084
2085 >>> if serverthread.serving:
2086 ... import webbrowser
2087
2088 The next two lines are commented out so a browser doesn't open if
2089 doctest is run on this module.
2090
2091 #... webbrowser.open(serverthread.url)
2092 #True
2093
2094 Let the server do its thing. We just need to monitor its status.
2095 Use time.sleep so the loop doesn't hog the CPU.
2096
2097 >>> starttime = time.time()
2098 >>> timeout = 1 #seconds
2099
2100 This is a short timeout for testing purposes.
2101
2102 >>> while serverthread.serving:
2103 ... time.sleep(.01)
2104 ... if serverthread.serving and time.time() - starttime > timeout:
2105 ... serverthread.stop()
2106 ... break
2107
2108 Print any errors that may have occurred.
2109
2110 >>> print(serverthread.error)
2111 None
2112 """
2113 import http.server
2114 import email.message
2115 import select
2116 import threading
2117
2118 class DocHandler(http.server.BaseHTTPRequestHandler):
2119
2120 def do_GET(self):
2121 """Process a request from an HTML browser.
2122
2123 The URL received is in self.path.
2124 Get an HTML page from self.urlhandler and send it.
2125 """
2126 if self.path.endswith('.css'):
2127 content_type = 'text/css'
2128 else:
2129 content_type = 'text/html'
2130 self.send_response(200)
Georg Brandld2f38572011-01-30 08:37:19 +00002131 self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002132 self.end_headers()
2133 self.wfile.write(self.urlhandler(
2134 self.path, content_type).encode('utf-8'))
2135
2136 def log_message(self, *args):
2137 # Don't log messages.
2138 pass
2139
2140 class DocServer(http.server.HTTPServer):
2141
2142 def __init__(self, port, callback):
2143 self.host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
2144 self.address = ('', port)
2145 self.callback = callback
2146 self.base.__init__(self, self.address, self.handler)
2147 self.quit = False
2148
2149 def serve_until_quit(self):
2150 while not self.quit:
2151 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
2152 if rd:
2153 self.handle_request()
Victor Stinnera3abd1d2011-01-03 16:12:39 +00002154 self.server_close()
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002155
2156 def server_activate(self):
2157 self.base.server_activate(self)
2158 if self.callback:
2159 self.callback(self)
2160
2161 class ServerThread(threading.Thread):
2162
2163 def __init__(self, urlhandler, port):
2164 self.urlhandler = urlhandler
2165 self.port = int(port)
2166 threading.Thread.__init__(self)
2167 self.serving = False
2168 self.error = None
2169
2170 def run(self):
2171 """Start the server."""
2172 try:
2173 DocServer.base = http.server.HTTPServer
2174 DocServer.handler = DocHandler
2175 DocHandler.MessageClass = email.message.Message
2176 DocHandler.urlhandler = staticmethod(self.urlhandler)
2177 docsvr = DocServer(self.port, self.ready)
2178 self.docserver = docsvr
2179 docsvr.serve_until_quit()
2180 except Exception as e:
2181 self.error = e
2182
2183 def ready(self, server):
2184 self.serving = True
2185 self.host = server.host
2186 self.port = server.server_port
2187 self.url = 'http://%s:%d/' % (self.host, self.port)
2188
2189 def stop(self):
2190 """Stop the server and this thread nicely"""
2191 self.docserver.quit = True
2192 self.serving = False
2193 self.url = None
2194
2195 thread = ServerThread(urlhandler, port)
2196 thread.start()
2197 # Wait until thread.serving is True to make sure we are
2198 # really up before returning.
2199 while not thread.error and not thread.serving:
2200 time.sleep(.01)
2201 return thread
2202
2203
2204def _url_handler(url, content_type="text/html"):
2205 """The pydoc url handler for use with the pydoc server.
2206
2207 If the content_type is 'text/css', the _pydoc.css style
2208 sheet is read and returned if it exits.
2209
2210 If the content_type is 'text/html', then the result of
2211 get_html_page(url) is returned.
2212 """
2213 class _HTMLDoc(HTMLDoc):
2214
2215 def page(self, title, contents):
2216 """Format an HTML page."""
2217 css_path = "pydoc_data/_pydoc.css"
2218 css_link = (
2219 '<link rel="stylesheet" type="text/css" href="%s">' %
2220 css_path)
2221 return '''\
2222<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Georg Brandld2f38572011-01-30 08:37:19 +00002223<html><head><title>Pydoc: %s</title>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002224<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Georg Brandld2f38572011-01-30 08:37:19 +00002225%s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div>
2226</body></html>''' % (title, css_link, html_navbar(), contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002227
2228 def filelink(self, url, path):
2229 return '<a href="getfile?key=%s">%s</a>' % (url, path)
2230
2231
2232 html = _HTMLDoc()
2233
2234 def html_navbar():
Georg Brandld2f38572011-01-30 08:37:19 +00002235 version = html.escape("%s [%s, %s]" % (platform.python_version(),
2236 platform.python_build()[0],
2237 platform.python_compiler()))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002238 return """
2239 <div style='float:left'>
Georg Brandld2f38572011-01-30 08:37:19 +00002240 Python %s<br>%s
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002241 </div>
2242 <div style='float:right'>
2243 <div style='text-align:center'>
2244 <a href="index.html">Module Index</a>
2245 : <a href="topics.html">Topics</a>
2246 : <a href="keywords.html">Keywords</a>
2247 </div>
2248 <div>
Georg Brandld2f38572011-01-30 08:37:19 +00002249 <form action="get" style='display:inline;'>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002250 <input type=text name=key size=15>
2251 <input type=submit value="Get">
Georg Brandld2f38572011-01-30 08:37:19 +00002252 </form>&nbsp;
2253 <form action="search" style='display:inline;'>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002254 <input type=text name=key size=15>
2255 <input type=submit value="Search">
2256 </form>
2257 </div>
2258 </div>
Georg Brandld2f38572011-01-30 08:37:19 +00002259 """ % (version, html.escape(platform.platform(terse=True)))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002260
2261 def html_index():
2262 """Module Index page."""
2263
2264 def bltinlink(name):
2265 return '<a href="%s.html">%s</a>' % (name, name)
2266
2267 heading = html.heading(
2268 '<big><big><strong>Index of Modules</strong></big></big>',
2269 '#ffffff', '#7799ee')
2270 names = [name for name in sys.builtin_module_names
2271 if name != '__main__']
2272 contents = html.multicolumn(names, bltinlink)
2273 contents = [heading, '<p>' + html.bigsection(
2274 'Built-in Modules', '#ffffff', '#ee77aa', contents)]
2275
2276 seen = {}
2277 for dir in sys.path:
2278 contents.append(html.index(dir, seen))
2279
2280 contents.append(
2281 '<p align=right><font color="#909090" face="helvetica,'
2282 'arial"><strong>pydoc</strong> by Ka-Ping Yee'
2283 '&lt;ping@lfw.org&gt;</font>')
Nick Coghlanecace282010-12-03 16:08:46 +00002284 return 'Index of Modules', ''.join(contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002285
2286 def html_search(key):
2287 """Search results page."""
2288 # scan for modules
2289 search_result = []
2290
2291 def callback(path, modname, desc):
2292 if modname[-9:] == '.__init__':
2293 modname = modname[:-9] + ' (package)'
2294 search_result.append((modname, desc and '- ' + desc))
2295
2296 with warnings.catch_warnings():
2297 warnings.filterwarnings('ignore') # ignore problems during import
2298 ModuleScanner().run(callback, key)
2299
2300 # format page
2301 def bltinlink(name):
2302 return '<a href="%s.html">%s</a>' % (name, name)
2303
2304 results = []
2305 heading = html.heading(
2306 '<big><big><strong>Search Results</strong></big></big>',
2307 '#ffffff', '#7799ee')
2308 for name, desc in search_result:
2309 results.append(bltinlink(name) + desc)
2310 contents = heading + html.bigsection(
2311 'key = %s' % key, '#ffffff', '#ee77aa', '<br>'.join(results))
Nick Coghlanecace282010-12-03 16:08:46 +00002312 return 'Search Results', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002313
2314 def html_getfile(path):
2315 """Get and display a source file listing safely."""
Nick Coghlanecace282010-12-03 16:08:46 +00002316 path = path.replace('%20', ' ')
Victor Stinner91e08772011-07-05 14:30:41 +02002317 with tokenize.open(path) as fp:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002318 lines = html.escape(fp.read())
2319 body = '<pre>%s</pre>' % lines
2320 heading = html.heading(
2321 '<big><big><strong>File Listing</strong></big></big>',
2322 '#ffffff', '#7799ee')
2323 contents = heading + html.bigsection(
2324 'File: %s' % path, '#ffffff', '#ee77aa', body)
Nick Coghlanecace282010-12-03 16:08:46 +00002325 return 'getfile %s' % path, contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002326
2327 def html_topics():
2328 """Index of topic texts available."""
2329
2330 def bltinlink(name):
Georg Brandld2f38572011-01-30 08:37:19 +00002331 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002332
2333 heading = html.heading(
2334 '<big><big><strong>INDEX</strong></big></big>',
2335 '#ffffff', '#7799ee')
2336 names = sorted(Helper.topics.keys())
2337
2338 contents = html.multicolumn(names, bltinlink)
2339 contents = heading + html.bigsection(
2340 'Topics', '#ffffff', '#ee77aa', contents)
Nick Coghlanecace282010-12-03 16:08:46 +00002341 return 'Topics', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002342
2343 def html_keywords():
2344 """Index of keywords."""
2345 heading = html.heading(
2346 '<big><big><strong>INDEX</strong></big></big>',
2347 '#ffffff', '#7799ee')
2348 names = sorted(Helper.keywords.keys())
2349
2350 def bltinlink(name):
Georg Brandld2f38572011-01-30 08:37:19 +00002351 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002352
2353 contents = html.multicolumn(names, bltinlink)
2354 contents = heading + html.bigsection(
2355 'Keywords', '#ffffff', '#ee77aa', contents)
Nick Coghlanecace282010-12-03 16:08:46 +00002356 return 'Keywords', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002357
2358 def html_topicpage(topic):
2359 """Topic or keyword help page."""
2360 buf = io.StringIO()
2361 htmlhelp = Helper(buf, buf)
2362 contents, xrefs = htmlhelp._gettopic(topic)
2363 if topic in htmlhelp.keywords:
2364 title = 'KEYWORD'
2365 else:
2366 title = 'TOPIC'
2367 heading = html.heading(
2368 '<big><big><strong>%s</strong></big></big>' % title,
2369 '#ffffff', '#7799ee')
Georg Brandld2f38572011-01-30 08:37:19 +00002370 contents = '<pre>%s</pre>' % html.markup(contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002371 contents = html.bigsection(topic , '#ffffff','#ee77aa', contents)
Georg Brandld2f38572011-01-30 08:37:19 +00002372 if xrefs:
2373 xrefs = sorted(xrefs.split())
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002374
Georg Brandld2f38572011-01-30 08:37:19 +00002375 def bltinlink(name):
2376 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002377
Georg Brandld2f38572011-01-30 08:37:19 +00002378 xrefs = html.multicolumn(xrefs, bltinlink)
2379 xrefs = html.section('Related help topics: ',
2380 '#ffffff', '#ee77aa', xrefs)
Nick Coghlanecace282010-12-03 16:08:46 +00002381 return ('%s %s' % (title, topic),
2382 ''.join((heading, contents, xrefs)))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002383
Georg Brandld2f38572011-01-30 08:37:19 +00002384 def html_getobj(url):
2385 obj = locate(url, forceload=1)
2386 if obj is None and url != 'None':
2387 raise ValueError('could not find object')
2388 title = describe(obj)
2389 content = html.document(obj, url)
2390 return title, content
2391
2392 def html_error(url, exc):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002393 heading = html.heading(
2394 '<big><big><strong>Error</strong></big></big>',
Georg Brandld2f38572011-01-30 08:37:19 +00002395 '#ffffff', '#7799ee')
2396 contents = '<br>'.join(html.escape(line) for line in
2397 format_exception_only(type(exc), exc))
2398 contents = heading + html.bigsection(url, '#ffffff', '#bb0000',
2399 contents)
2400 return "Error - %s" % url, contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002401
2402 def get_html_page(url):
2403 """Generate an HTML page for url."""
Georg Brandld2f38572011-01-30 08:37:19 +00002404 complete_url = url
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002405 if url.endswith('.html'):
2406 url = url[:-5]
Georg Brandld2f38572011-01-30 08:37:19 +00002407 try:
2408 if url in ("", "index"):
2409 title, content = html_index()
2410 elif url == "topics":
2411 title, content = html_topics()
2412 elif url == "keywords":
2413 title, content = html_keywords()
2414 elif '=' in url:
2415 op, _, url = url.partition('=')
2416 if op == "search?key":
2417 title, content = html_search(url)
2418 elif op == "getfile?key":
2419 title, content = html_getfile(url)
2420 elif op == "topic?key":
2421 # try topics first, then objects.
2422 try:
2423 title, content = html_topicpage(url)
2424 except ValueError:
2425 title, content = html_getobj(url)
2426 elif op == "get?key":
2427 # try objects first, then topics.
2428 if url in ("", "index"):
2429 title, content = html_index()
2430 else:
2431 try:
2432 title, content = html_getobj(url)
2433 except ValueError:
2434 title, content = html_topicpage(url)
2435 else:
2436 raise ValueError('bad pydoc url')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002437 else:
Georg Brandld2f38572011-01-30 08:37:19 +00002438 title, content = html_getobj(url)
2439 except Exception as exc:
2440 # Catch any errors and display them in an error page.
2441 title, content = html_error(complete_url, exc)
2442 return html.page(title, content)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002443
2444 if url.startswith('/'):
2445 url = url[1:]
2446 if content_type == 'text/css':
2447 path_here = os.path.dirname(os.path.realpath(__file__))
Georg Brandld2f38572011-01-30 08:37:19 +00002448 css_path = os.path.join(path_here, url)
2449 with open(css_path) as fp:
2450 return ''.join(fp.readlines())
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002451 elif content_type == 'text/html':
2452 return get_html_page(url)
Georg Brandld2f38572011-01-30 08:37:19 +00002453 # Errors outside the url handler are caught by the server.
2454 raise TypeError('unknown content type %r for url %s' % (content_type, url))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002455
2456
2457def browse(port=0, *, open_browser=True):
2458 """Start the enhanced pydoc Web server and open a Web browser.
2459
2460 Use port '0' to start the server on an arbitrary port.
2461 Set open_browser to False to suppress opening a browser.
2462 """
2463 import webbrowser
2464 serverthread = _start_server(_url_handler, port)
2465 if serverthread.error:
2466 print(serverthread.error)
2467 return
2468 if serverthread.serving:
2469 server_help_msg = 'Server commands: [b]rowser, [q]uit'
2470 if open_browser:
2471 webbrowser.open(serverthread.url)
2472 try:
2473 print('Server ready at', serverthread.url)
2474 print(server_help_msg)
2475 while serverthread.serving:
2476 cmd = input('server> ')
2477 cmd = cmd.lower()
2478 if cmd == 'q':
2479 break
2480 elif cmd == 'b':
2481 webbrowser.open(serverthread.url)
2482 else:
2483 print(server_help_msg)
2484 except (KeyboardInterrupt, EOFError):
2485 print()
2486 finally:
2487 if serverthread.serving:
2488 serverthread.stop()
2489 print('Server stopped')
2490
2491
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002492# -------------------------------------------------- command-line interface
2493
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002494def ispath(x):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002495 return isinstance(x, str) and x.find(os.sep) >= 0
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002496
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002497def cli():
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002498 """Command-line interface (looks at sys.argv to decide what to do)."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002499 import getopt
Guido van Rossum756aa932007-04-07 03:04:01 +00002500 class BadUsage(Exception): pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002501
Nick Coghlan106274b2009-11-15 23:04:33 +00002502 # Scripts don't get the current directory in their path by default
2503 # unless they are run with the '-m' switch
2504 if '' not in sys.path:
2505 scriptdir = os.path.dirname(sys.argv[0])
2506 if scriptdir in sys.path:
2507 sys.path.remove(scriptdir)
2508 sys.path.insert(0, '.')
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002509
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00002510 try:
Victor Stinner383c3fc2011-05-25 01:35:05 +02002511 opts, args = getopt.getopt(sys.argv[1:], 'bk:p:w')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002512 writing = False
2513 start_server = False
2514 open_browser = False
2515 port = None
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002516 for opt, val in opts:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002517 if opt == '-b':
2518 start_server = True
2519 open_browser = True
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002520 if opt == '-k':
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002521 apropos(val)
2522 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002523 if opt == '-p':
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002524 start_server = True
2525 port = val
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002526 if opt == '-w':
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002527 writing = True
2528
Benjamin Petersonb29614e2012-10-09 11:16:03 -04002529 if start_server:
2530 if port is None:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002531 port = 0
2532 browse(port, open_browser=open_browser)
2533 return
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002534
2535 if not args: raise BadUsage
2536 for arg in args:
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00002537 if ispath(arg) and not os.path.exists(arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002538 print('file %r does not exist' % arg)
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00002539 break
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002540 try:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002541 if ispath(arg) and os.path.isfile(arg):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002542 arg = importfile(arg)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002543 if writing:
2544 if ispath(arg) and os.path.isdir(arg):
2545 writedocs(arg)
2546 else:
2547 writedoc(arg)
2548 else:
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002549 help.help(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +00002550 except ErrorDuringImport as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002551 print(value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002552
2553 except (getopt.error, BadUsage):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002554 cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002555 print("""pydoc - the Python documentation tool
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002556
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002557{cmd} <name> ...
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002558 Show text documentation on something. <name> may be the name of a
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002559 Python keyword, topic, function, module, or package, or a dotted
2560 reference to a class or function within a module or module in a
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002561 package. If <name> contains a '{sep}', it is used as the path to a
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002562 Python source file to document. If name is 'keywords', 'topics',
2563 or 'modules', a listing of these things is displayed.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002564
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002565{cmd} -k <keyword>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002566 Search for a keyword in the synopsis lines of all available modules.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002567
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002568{cmd} -p <port>
2569 Start an HTTP server on the given port on the local machine. Port
2570 number 0 can be used to get an arbitrary unused port.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002571
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002572{cmd} -b
2573 Start an HTTP server on an arbitrary unused port and open a Web browser
2574 to interactively browse documentation. The -p option can be used with
2575 the -b option to explicitly specify the server port.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002576
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002577{cmd} -w <name> ...
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002578 Write out the HTML documentation for a module to a file in the current
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002579 directory. If <name> contains a '{sep}', it is treated as a filename; if
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00002580 it names a directory, documentation is written for all the contents.
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002581""".format(cmd=cmd, sep=os.sep))
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002582
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002583if __name__ == '__main__':
2584 cli()