blob: 86ccfe041f6675e20af0aebd1378e406e1306941 [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
R David Murray3d050dd2014-04-19 12:59:30 -04004At the Python interactive prompt, calling help(thing) on a Python object
5documents the object, and calling help() starts up an interactive
6help session.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00007
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00008Or, at the shell command line outside of Python:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00009
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000010Run "pydoc <name>" to show documentation on something. <name> may be
11the name of a function, module, package, or a dotted reference to a
12class or function within a module or module in a package. If the
13argument contains a path segment delimiter (e.g. slash on Unix,
14backslash on Windows) it is treated as the path to a Python source file.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000015
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000016Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
17of all available modules.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000018
Feanil Patel6a396c92017-09-14 17:54:09 -040019Run "pydoc -n <hostname>" to start an HTTP server with the given
20hostname (default: localhost) on the local machine.
21
Nick Coghlan7bb30b72010-12-03 09:29:11 +000022Run "pydoc -p <port>" to start an HTTP server on the given port on the
23local machine. Port number 0 can be used to get an arbitrary unused port.
24
25Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
Feanil Patel6a396c92017-09-14 17:54:09 -040026open a Web browser to interactively browse documentation. Combine with
27the -n and -p options to control the hostname and port used.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000028
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000029Run "pydoc -w <name>" to write out the HTML documentation for a module
30to a file named "<name>.html".
Skip Montanaro4997a692003-09-10 16:47:51 +000031
32Module docs for core modules are assumed to be in
33
Martin Panter4f8aaf62016-06-12 04:24:06 +000034 https://docs.python.org/X.Y/library/
Skip Montanaro4997a692003-09-10 16:47:51 +000035
36This can be overridden by setting the PYTHONDOCS environment variable
37to a different URL or to a local directory containing the Library
38Reference Manual pages.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000039"""
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000040__all__ = ['help']
Ka-Ping Yeedd175342001-02-27 14:43:46 +000041__author__ = "Ka-Ping Yee <ping@lfw.org>"
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000042__date__ = "26 February 2001"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043
Martin v. Löwis6fe8f192004-11-14 10:21:04 +000044__credits__ = """Guido van Rossum, for an excellent programming language.
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000045Tommy Burnette, the original creator of manpy.
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000046Paul Prescod, for all his work on onlinehelp.
47Richard Chamberlain, for the first implementation of textdoc.
Raymond Hettingered2dbe32005-01-01 07:51:01 +000048"""
Ka-Ping Yeedd175342001-02-27 14:43:46 +000049
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000050# Known bugs that can't be fixed here:
Brett Cannonf4ba4ec2013-06-15 14:25:04 -040051# - synopsis() cannot be prevented from clobbering existing
52# loaded modules.
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000053# - If the __file__ attribute on a module is a relative path and
54# the current directory is changed with os.chdir(), an incorrect
55# path will be displayed.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000056
Nick Coghlan7bb30b72010-12-03 09:29:11 +000057import builtins
Brett Cannond5e6f2e2013-06-11 17:09:36 -040058import importlib._bootstrap
Eric Snow32439d62015-05-02 19:15:18 -060059import importlib._bootstrap_external
Brett Cannoncb66eb02012-05-11 12:58:42 -040060import importlib.machinery
Brett Cannonf4ba4ec2013-06-15 14:25:04 -040061import importlib.util
Nick Coghlan7bb30b72010-12-03 09:29:11 +000062import inspect
Victor Stinnere6c910e2011-06-30 15:55:43 +020063import io
64import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +000065import pkgutil
66import platform
67import re
Victor Stinnere6c910e2011-06-30 15:55:43 +020068import sys
Nick Coghlan7bb30b72010-12-03 09:29:11 +000069import time
Victor Stinnere6c910e2011-06-30 15:55:43 +020070import tokenize
Zachary Wareeb432142014-07-10 11:18:00 -050071import urllib.parse
Nick Coghlan7bb30b72010-12-03 09:29:11 +000072import warnings
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000073from collections import deque
Nick Coghlan7bb30b72010-12-03 09:29:11 +000074from reprlib import Repr
Victor Stinner7fa767e2014-03-20 09:16:38 +010075from traceback import format_exception_only
Nick Coghlan7bb30b72010-12-03 09:29:11 +000076
77
Ka-Ping Yeedd175342001-02-27 14:43:46 +000078# --------------------------------------------------------- common routines
79
Ka-Ping Yeedd175342001-02-27 14:43:46 +000080def pathdirs():
81 """Convert sys.path into a list of absolute, existing, unique paths."""
82 dirs = []
Ka-Ping Yee1d384632001-03-01 00:24:32 +000083 normdirs = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +000084 for dir in sys.path:
85 dir = os.path.abspath(dir or '.')
Ka-Ping Yee1d384632001-03-01 00:24:32 +000086 normdir = os.path.normcase(dir)
87 if normdir not in normdirs and os.path.isdir(dir):
Ka-Ping Yeedd175342001-02-27 14:43:46 +000088 dirs.append(dir)
Ka-Ping Yee1d384632001-03-01 00:24:32 +000089 normdirs.append(normdir)
Ka-Ping Yeedd175342001-02-27 14:43:46 +000090 return dirs
91
92def getdoc(object):
93 """Get the doc string or comments for an object."""
Ka-Ping Yee3bda8792001-03-23 13:17:50 +000094 result = inspect.getdoc(object) or inspect.getcomments(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +000095 return result and re.sub('^ *\n', '', result.rstrip()) or ''
Ka-Ping Yeedd175342001-02-27 14:43:46 +000096
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000097def splitdoc(doc):
98 """Split a doc string into a synopsis line (if any) and the rest."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +000099 lines = doc.strip().split('\n')
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000100 if len(lines) == 1:
101 return lines[0], ''
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000102 elif len(lines) >= 2 and not lines[1].rstrip():
103 return lines[0], '\n'.join(lines[2:])
104 return '', '\n'.join(lines)
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000105
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000106def classname(object, modname):
107 """Get a class name and qualify it with a module name if necessary."""
108 name = object.__name__
109 if object.__module__ != modname:
110 name = object.__module__ + '.' + name
111 return name
112
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000113def isdata(object):
Georg Brandl94432422005-07-22 21:52:25 +0000114 """Check if an object is of a type that probably means it's data."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000115 return not (inspect.ismodule(object) or inspect.isclass(object) or
116 inspect.isroutine(object) or inspect.isframe(object) or
117 inspect.istraceback(object) or inspect.iscode(object))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000118
119def replace(text, *pairs):
120 """Do a series of global replacements on a string."""
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000121 while pairs:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000122 text = pairs[1].join(text.split(pairs[0]))
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000123 pairs = pairs[2:]
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000124 return text
125
126def cram(text, maxlen):
127 """Omit part of a string if needed to make it fit in a maximum length."""
128 if len(text) > maxlen:
Raymond Hettingerfca3bb62002-10-21 04:44:11 +0000129 pre = max(0, (maxlen-3)//2)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000130 post = max(0, maxlen-3-pre)
131 return text[:pre] + '...' + text[len(text)-post:]
132 return text
133
Brett Cannon84601f12004-06-19 01:22:48 +0000134_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000135def stripid(text):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000136 """Remove the hexadecimal id from a Python object representation."""
Brett Cannonc6c1f472004-06-19 01:02:51 +0000137 # The behaviour of %p is implementation-dependent in terms of case.
Ezio Melotti412c95a2010-02-16 23:31:04 +0000138 return _re_stripid.sub(r'\1', text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000139
Larry Hastings24a882b2014-02-20 23:34:46 -0800140def _is_bound_method(fn):
141 """
142 Returns True if fn is a bound method, regardless of whether
143 fn was implemented in Python or in C.
144 """
145 if inspect.ismethod(fn):
146 return True
147 if inspect.isbuiltin(fn):
148 self = getattr(fn, '__self__', None)
149 return not (inspect.ismodule(self) or (self is None))
150 return False
151
152
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000153def allmethods(cl):
154 methods = {}
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +0200155 for key, value in inspect.getmembers(cl, inspect.isroutine):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000156 methods[key] = 1
157 for base in cl.__bases__:
158 methods.update(allmethods(base)) # all your base are belong to us
159 for key in methods.keys():
160 methods[key] = getattr(cl, key)
161 return methods
162
Tim Petersfa26f7c2001-09-24 08:05:11 +0000163def _split_list(s, predicate):
164 """Split sequence s via predicate, and return pair ([true], [false]).
165
166 The return value is a 2-tuple of lists,
167 ([x for x in s if predicate(x)],
168 [x for x in s if not predicate(x)])
169 """
170
Tim Peters28355492001-09-23 21:29:55 +0000171 yes = []
172 no = []
Tim Petersfa26f7c2001-09-24 08:05:11 +0000173 for x in s:
174 if predicate(x):
175 yes.append(x)
Tim Peters28355492001-09-23 21:29:55 +0000176 else:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000177 no.append(x)
Tim Peters28355492001-09-23 21:29:55 +0000178 return yes, no
179
Raymond Hettinger1103d052011-03-25 14:15:24 -0700180def visiblename(name, all=None, obj=None):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000181 """Decide whether to show documentation on a variable."""
Brett Cannond340b432012-08-06 17:19:22 -0400182 # Certain special names are redundant or internal.
Eric Snowb523f842013-11-22 09:05:39 -0700183 # XXX Remove __initializing__?
Brett Cannond340b432012-08-06 17:19:22 -0400184 if name in {'__author__', '__builtins__', '__cached__', '__credits__',
Eric Snowb523f842013-11-22 09:05:39 -0700185 '__date__', '__doc__', '__file__', '__spec__',
Brett Cannond340b432012-08-06 17:19:22 -0400186 '__loader__', '__module__', '__name__', '__package__',
187 '__path__', '__qualname__', '__slots__', '__version__'}:
Raymond Hettinger68272942011-03-18 02:22:15 -0700188 return 0
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000189 # Private names are hidden, but special names are displayed.
190 if name.startswith('__') and name.endswith('__'): return 1
Raymond Hettinger1103d052011-03-25 14:15:24 -0700191 # Namedtuples have public fields and methods with a single leading underscore
192 if name.startswith('_') and hasattr(obj, '_fields'):
193 return True
Skip Montanaroa5616d22004-06-11 04:46:12 +0000194 if all is not None:
195 # only document that which the programmer exported in __all__
196 return name in all
197 else:
198 return not name.startswith('_')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000199
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000200def classify_class_attrs(object):
201 """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000202 results = []
203 for (name, kind, cls, value) in inspect.classify_class_attrs(object):
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000204 if inspect.isdatadescriptor(value):
205 kind = 'data descriptor'
Raymond Hettinger62be3382019-03-24 17:07:47 -0700206 if isinstance(value, property) and value.fset is None:
207 kind = 'readonly property'
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000208 results.append((name, kind, cls, value))
209 return results
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000210
Raymond Hettinger95801bb2015-08-18 22:25:16 -0700211def sort_attributes(attrs, object):
212 'Sort the attrs list in-place by _fields and then alphabetically by name'
213 # This allows data descriptors to be ordered according
214 # to a _fields attribute if present.
215 fields = getattr(object, '_fields', [])
216 try:
217 field_order = {name : i-len(fields) for (i, name) in enumerate(fields)}
218 except TypeError:
219 field_order = {}
220 keyfunc = lambda attr: (field_order.get(attr[0], 0), attr[0])
221 attrs.sort(key=keyfunc)
222
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000223# ----------------------------------------------------- module manipulation
224
225def ispackage(path):
226 """Guess whether a path refers to a package directory."""
227 if os.path.isdir(path):
Brett Cannonf299abd2015-04-13 14:21:02 -0400228 for ext in ('.py', '.pyc'):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000229 if os.path.isfile(os.path.join(path, '__init__' + ext)):
Tim Petersbc0e9102002-04-04 22:55:58 +0000230 return True
231 return False
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000232
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000233def source_synopsis(file):
234 line = file.readline()
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000235 while line[:1] == '#' or not line.strip():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000236 line = file.readline()
237 if not line: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000238 line = line.strip()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000239 if line[:4] == 'r"""': line = line[1:]
240 if line[:3] == '"""':
241 line = line[3:]
242 if line[-1:] == '\\': line = line[:-1]
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000243 while not line.strip():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244 line = file.readline()
245 if not line: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000246 result = line.split('"""')[0].strip()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247 else: result = None
248 return result
249
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000250def synopsis(filename, cache={}):
251 """Get the one-line summary out of a module file."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000252 mtime = os.stat(filename).st_mtime
Charles-François Natali27c4e882011-07-27 19:40:02 +0200253 lastupdate, result = cache.get(filename, (None, None))
254 if lastupdate is None or lastupdate < mtime:
Eric Snowaed5b222014-01-04 20:38:11 -0700255 # Look for binary suffixes first, falling back to source.
256 if filename.endswith(tuple(importlib.machinery.BYTECODE_SUFFIXES)):
257 loader_cls = importlib.machinery.SourcelessFileLoader
258 elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
259 loader_cls = importlib.machinery.ExtensionFileLoader
260 else:
261 loader_cls = None
262 # Now handle the choice.
263 if loader_cls is None:
264 # Must be a source file.
265 try:
266 file = tokenize.open(filename)
267 except OSError:
268 # module can't be opened, so skip it
269 return None
270 # text modules can be directly examined
271 with file:
272 result = source_synopsis(file)
273 else:
274 # Must be a binary module, which has to be imported.
275 loader = loader_cls('__temp__', filename)
Eric Snow3a62d142014-01-06 20:42:59 -0700276 # XXX We probably don't need to pass in the loader here.
277 spec = importlib.util.spec_from_file_location('__temp__', filename,
278 loader=loader)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400279 try:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400280 module = importlib._bootstrap._load(spec)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400281 except:
282 return None
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000283 del sys.modules['__temp__']
Benjamin Peterson54237f92015-02-16 19:45:01 -0500284 result = module.__doc__.splitlines()[0] if module.__doc__ else None
Eric Snowaed5b222014-01-04 20:38:11 -0700285 # Cache the result.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000286 cache[filename] = (mtime, result)
287 return result
288
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000289class ErrorDuringImport(Exception):
290 """Errors that occurred while trying to import something to document it."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000291 def __init__(self, filename, exc_info):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000292 self.filename = filename
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000293 self.exc, self.value, self.tb = exc_info
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000294
295 def __str__(self):
Guido van Rossuma01a8b62007-05-27 09:20:14 +0000296 exc = self.exc.__name__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000297 return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000298
299def importfile(path):
300 """Import a Python source file or compiled file given its path."""
Brett Cannonf4ba4ec2013-06-15 14:25:04 -0400301 magic = importlib.util.MAGIC_NUMBER
Victor Stinnere975af62011-07-04 02:08:50 +0200302 with open(path, 'rb') as file:
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400303 is_bytecode = magic == file.read(len(magic))
304 filename = os.path.basename(path)
305 name, ext = os.path.splitext(filename)
306 if is_bytecode:
Eric Snow32439d62015-05-02 19:15:18 -0600307 loader = importlib._bootstrap_external.SourcelessFileLoader(name, path)
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400308 else:
Eric Snow32439d62015-05-02 19:15:18 -0600309 loader = importlib._bootstrap_external.SourceFileLoader(name, path)
Eric Snow3a62d142014-01-06 20:42:59 -0700310 # XXX We probably don't need to pass in the loader here.
311 spec = importlib.util.spec_from_file_location(name, path, loader=loader)
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400312 try:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400313 return importlib._bootstrap._load(spec)
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400314 except:
315 raise ErrorDuringImport(path, sys.exc_info())
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000316
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000317def safeimport(path, forceload=0, cache={}):
318 """Import a module; handle errors; return None if the module isn't found.
319
320 If the module *is* found but an exception occurs, it's wrapped in an
321 ErrorDuringImport exception and reraised. Unlike __import__, if a
322 package path is specified, the module at the end of the path is returned,
323 not the package at the beginning. If the optional 'forceload' argument
324 is 1, we reload the module from disk (unless it's a dynamic extension)."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000325 try:
Ka-Ping Yee9a2dcf82005-11-05 05:04:41 +0000326 # If forceload is 1 and the module has been previously loaded from
327 # disk, we always have to reload the module. Checking the file's
328 # mtime isn't good enough (e.g. the module could contain a class
329 # that inherits from another module that has changed).
330 if forceload and path in sys.modules:
331 if path not in sys.builtin_module_names:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000332 # Remove the module from sys.modules and re-import to try
333 # and avoid problems with partially loaded modules.
334 # Also remove any submodules because they won't appear
335 # in the newly loaded module's namespace if they're already
336 # in sys.modules.
Ka-Ping Yee9a2dcf82005-11-05 05:04:41 +0000337 subs = [m for m in sys.modules if m.startswith(path + '.')]
338 for key in [path] + subs:
339 # Prevent garbage collection.
340 cache[key] = sys.modules[key]
341 del sys.modules[key]
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000342 module = __import__(path)
343 except:
344 # Did the error occur before or after the module was found?
345 (exc, value, tb) = info = sys.exc_info()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000346 if path in sys.modules:
Fred Drakedb390c12005-10-28 14:39:47 +0000347 # An error occurred while executing the imported module.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000348 raise ErrorDuringImport(sys.modules[path].__file__, info)
349 elif exc is SyntaxError:
350 # A SyntaxError occurred before we could execute the module.
351 raise ErrorDuringImport(value.filename, info)
Eric Snow46f97b82016-09-07 16:56:15 -0700352 elif issubclass(exc, ImportError) and value.name == path:
Brett Cannonfd074152012-04-14 14:10:13 -0400353 # No such module in the path.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000354 return None
355 else:
356 # Some other error occurred during the importing process.
357 raise ErrorDuringImport(path, sys.exc_info())
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000358 for part in path.split('.')[1:]:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000359 try: module = getattr(module, part)
360 except AttributeError: return None
361 return module
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000362
363# ---------------------------------------------------- formatter base class
364
365class Doc:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000366
367 PYTHONDOCS = os.environ.get("PYTHONDOCS",
R David Murrayead9bfc2016-06-03 19:28:35 -0400368 "https://docs.python.org/%d.%d/library"
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000369 % sys.version_info[:2])
370
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000371 def document(self, object, name=None, *args):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000372 """Generate documentation for an object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000373 args = (object, name) + args
Brett Cannon28a4f0f2003-06-11 23:38:55 +0000374 # 'try' clause is to attempt to handle the possibility that inspect
375 # identifies something in a way that pydoc itself has issues handling;
376 # think 'super' and how it is a descriptor (which raises the exception
377 # by lacking a __name__ attribute) and an instance.
378 try:
379 if inspect.ismodule(object): return self.docmodule(*args)
380 if inspect.isclass(object): return self.docclass(*args)
381 if inspect.isroutine(object): return self.docroutine(*args)
382 except AttributeError:
383 pass
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +0200384 if inspect.isdatadescriptor(object): return self.docdata(*args)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000385 return self.docother(*args)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000386
387 def fail(self, object, name=None, *args):
388 """Raise an exception for unimplemented types."""
389 message = "don't know how to document object%s of type %s" % (
390 name and ' ' + repr(name), type(object).__name__)
Collin Winterce36ad82007-08-30 01:19:48 +0000391 raise TypeError(message)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000392
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000393 docmodule = docclass = docroutine = docother = docproperty = docdata = fail
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000394
R David Murrayead9bfc2016-06-03 19:28:35 -0400395 def getdocloc(self, object,
396 basedir=os.path.join(sys.base_exec_prefix, "lib",
397 "python%d.%d" % sys.version_info[:2])):
Skip Montanaro4997a692003-09-10 16:47:51 +0000398 """Return the location of module docs or None"""
399
400 try:
401 file = inspect.getabsfile(object)
402 except TypeError:
403 file = '(built-in)'
404
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000405 docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
406
Martin Panter4f8aaf62016-06-12 04:24:06 +0000407 basedir = os.path.normcase(basedir)
Skip Montanaro4997a692003-09-10 16:47:51 +0000408 if (isinstance(object, type(os)) and
409 (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
410 'marshal', 'posix', 'signal', 'sys',
Georg Brandl2067bfd2008-05-25 13:05:15 +0000411 '_thread', 'zipimport') or
Skip Montanaro4997a692003-09-10 16:47:51 +0000412 (file.startswith(basedir) and
Brian Curtin49c284c2010-03-31 03:19:28 +0000413 not file.startswith(os.path.join(basedir, 'site-packages')))) and
Brian Curtinedef05b2010-04-01 04:05:25 +0000414 object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
Martin Panter4f8aaf62016-06-12 04:24:06 +0000415 if docloc.startswith(("http://", "https://")):
R David Murrayead9bfc2016-06-03 19:28:35 -0400416 docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower())
Skip Montanaro4997a692003-09-10 16:47:51 +0000417 else:
R David Murrayead9bfc2016-06-03 19:28:35 -0400418 docloc = os.path.join(docloc, object.__name__.lower() + ".html")
Skip Montanaro4997a692003-09-10 16:47:51 +0000419 else:
420 docloc = None
421 return docloc
422
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000423# -------------------------------------------- HTML documentation generator
424
425class HTMLRepr(Repr):
426 """Class for safely making an HTML representation of a Python object."""
427 def __init__(self):
428 Repr.__init__(self)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000429 self.maxlist = self.maxtuple = 20
430 self.maxdict = 10
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000431 self.maxstring = self.maxother = 100
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000432
433 def escape(self, text):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000434 return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000435
436 def repr(self, object):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000437 return Repr.repr(self, object)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000438
439 def repr1(self, x, level):
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000440 if hasattr(type(x), '__name__'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000441 methodname = 'repr_' + '_'.join(type(x).__name__.split())
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000442 if hasattr(self, methodname):
443 return getattr(self, methodname)(x, level)
444 return self.escape(cram(stripid(repr(x)), self.maxother))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000445
446 def repr_string(self, x, level):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000447 test = cram(x, self.maxstring)
448 testrepr = repr(test)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000449 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000450 # Backslashes are only literal in the string and are never
451 # needed to make any special characters, so show a raw string.
452 return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000453 return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000454 r'<font color="#c040c0">\1</font>',
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000455 self.escape(testrepr))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000456
Skip Montanarodf708782002-03-07 22:58:02 +0000457 repr_str = repr_string
458
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000459 def repr_instance(self, x, level):
460 try:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000461 return self.escape(cram(stripid(repr(x)), self.maxstring))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000462 except:
463 return self.escape('<%s instance>' % x.__class__.__name__)
464
465 repr_unicode = repr_string
466
467class HTMLDoc(Doc):
468 """Formatter class for HTML documentation."""
469
470 # ------------------------------------------- HTML formatting utilities
471
472 _repr_instance = HTMLRepr()
473 repr = _repr_instance.repr
474 escape = _repr_instance.escape
475
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000476 def page(self, title, contents):
477 """Format an HTML page."""
Georg Brandl388faac2009-04-10 08:31:48 +0000478 return '''\
Georg Brandle6066942009-04-10 08:28:28 +0000479<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000480<html><head><title>Python: %s</title>
Georg Brandl388faac2009-04-10 08:31:48 +0000481<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000482</head><body bgcolor="#f0f0f8">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000483%s
484</body></html>''' % (title, contents)
485
486 def heading(self, title, fgcol, bgcol, extras=''):
487 """Format a page heading."""
488 return '''
Tim Peters59ed4482001-10-31 04:20:26 +0000489<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000490<tr bgcolor="%s">
Tim Peters2306d242001-09-25 03:18:32 +0000491<td valign=bottom>&nbsp;<br>
492<font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000493><td align=right valign=bottom
Ka-Ping Yee987ec902001-03-23 13:35:45 +0000494><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000495 ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
496
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000497 def section(self, title, fgcol, bgcol, contents, width=6,
498 prelude='', marginalia=None, gap='&nbsp;'):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000499 """Format a section with a heading."""
500 if marginalia is None:
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000501 marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000502 result = '''<p>
Tim Peters59ed4482001-10-31 04:20:26 +0000503<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000504<tr bgcolor="%s">
Tim Peters2306d242001-09-25 03:18:32 +0000505<td colspan=3 valign=bottom>&nbsp;<br>
506<font color="%s" face="helvetica, arial">%s</font></td></tr>
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000507 ''' % (bgcol, fgcol, title)
508 if prelude:
509 result = result + '''
Ka-Ping Yee987ec902001-03-23 13:35:45 +0000510<tr bgcolor="%s"><td rowspan=2>%s</td>
511<td colspan=2>%s</td></tr>
512<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
513 else:
514 result = result + '''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000515<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000516
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000517 return result + '\n<td width="100%%">%s</td></tr></table>' % contents
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000518
519 def bigsection(self, title, *args):
520 """Format a section with a big heading."""
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000521 title = '<big><strong>%s</strong></big>' % title
Guido van Rossum68468eb2003-02-27 20:14:51 +0000522 return self.section(title, *args)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000523
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000524 def preformat(self, text):
525 """Format literal preformatted text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000526 text = self.escape(text.expandtabs())
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000527 return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
528 ' ', '&nbsp;', '\n', '<br>\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000529
530 def multicolumn(self, list, format, cols=4):
531 """Format a list of items into a multi-column list."""
532 result = ''
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000533 rows = (len(list)+cols-1)//cols
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000534 for col in range(cols):
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000535 result = result + '<td width="%d%%" valign=top>' % (100//cols)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000536 for i in range(rows*col, rows*col+rows):
537 if i < len(list):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000538 result = result + format(list[i]) + '<br>\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000539 result = result + '</td>'
Tim Peters59ed4482001-10-31 04:20:26 +0000540 return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000541
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000542 def grey(self, text): return '<font color="#909090">%s</font>' % text
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000543
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000544 def namelink(self, name, *dicts):
545 """Make a link for an identifier, given name-to-URL mappings."""
546 for dict in dicts:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000547 if name in dict:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000548 return '<a href="%s">%s</a>' % (dict[name], name)
549 return name
550
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000551 def classlink(self, object, modname):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000552 """Make a link for a class."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000553 name, module = object.__name__, sys.modules.get(object.__module__)
554 if hasattr(module, name) and getattr(module, name) is object:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000555 return '<a href="%s.html#%s">%s</a>' % (
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000556 module.__name__, name, classname(object, modname))
557 return classname(object, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000558
559 def modulelink(self, object):
560 """Make a link for a module."""
561 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
562
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000563 def modpkglink(self, modpkginfo):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000564 """Make a link for a module or package to display in an index."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000565 name, path, ispackage, shadowed = modpkginfo
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000566 if shadowed:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000567 return self.grey(name)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000568 if path:
569 url = '%s.%s.html' % (path, name)
570 else:
571 url = '%s.html' % name
572 if ispackage:
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000573 text = '<strong>%s</strong>&nbsp;(package)' % name
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000574 else:
575 text = name
576 return '<a href="%s">%s</a>' % (url, text)
577
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000578 def filelink(self, url, path):
579 """Make a link to source file."""
580 return '<a href="file:%s">%s</a>' % (url, path)
581
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000582 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
583 """Mark up some plain text, given a context of symbols to look for.
584 Each context dictionary maps object names to anchor names."""
585 escape = escape or self.escape
586 results = []
587 here = 0
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000588 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
589 r'RFC[- ]?(\d+)|'
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000590 r'PEP[- ]?(\d+)|'
Neil Schemenauerd69711c2002-03-24 23:02:07 +0000591 r'(self\.)?(\w+))')
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000592 while True:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000593 match = pattern.search(text, here)
594 if not match: break
595 start, end = match.span()
596 results.append(escape(text[here:start]))
597
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000598 all, scheme, rfc, pep, selfdot, name = match.groups()
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000599 if scheme:
Neil Schemenauercddc1a02002-03-24 23:11:21 +0000600 url = escape(all).replace('"', '&quot;')
601 results.append('<a href="%s">%s</a>' % (url, url))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000602 elif rfc:
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000603 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
604 results.append('<a href="%s">%s</a>' % (url, escape(all)))
605 elif pep:
Christian Heimes2202f872008-02-06 14:31:34 +0000606 url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000607 results.append('<a href="%s">%s</a>' % (url, escape(all)))
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700608 elif selfdot:
609 # Create a link for methods like 'self.method(...)'
610 # and use <strong> for attributes like 'self.attr'
611 if text[end:end+1] == '(':
612 results.append('self.' + self.namelink(name, methods))
613 else:
614 results.append('self.<strong>%s</strong>' % name)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000615 elif text[end:end+1] == '(':
616 results.append(self.namelink(name, methods, funcs, classes))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000617 else:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000618 results.append(self.namelink(name, classes))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000619 here = end
620 results.append(escape(text[here:]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000621 return ''.join(results)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000622
623 # ---------------------------------------------- type-specific routines
624
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000625 def formattree(self, tree, modname, parent=None):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000626 """Produce HTML for a class tree as given by inspect.getclasstree()."""
627 result = ''
628 for entry in tree:
629 if type(entry) is type(()):
630 c, bases = entry
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000631 result = result + '<dt><font face="helvetica, arial">'
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000632 result = result + self.classlink(c, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000633 if bases and bases != (parent,):
634 parents = []
635 for base in bases:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000636 parents.append(self.classlink(base, modname))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000637 result = result + '(' + ', '.join(parents) + ')'
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000638 result = result + '\n</font></dt>'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000639 elif type(entry) is type([]):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000640 result = result + '<dd>\n%s</dd>\n' % self.formattree(
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000641 entry, modname, c)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000642 return '<dl>\n%s</dl>\n' % result
643
Tim Peters8dd7ade2001-10-18 19:56:17 +0000644 def docmodule(self, object, name=None, mod=None, *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000645 """Produce HTML documentation for a module object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000646 name = object.__name__ # ignore the passed-in name
Skip Montanaroa5616d22004-06-11 04:46:12 +0000647 try:
648 all = object.__all__
649 except AttributeError:
650 all = None
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000651 parts = name.split('.')
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000652 links = []
653 for i in range(len(parts)-1):
654 links.append(
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000655 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000656 ('.'.join(parts[:i+1]), parts[i]))
657 linkedname = '.'.join(links + parts[-1:])
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000658 head = '<big><big><strong>%s</strong></big></big>' % linkedname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000659 try:
Ka-Ping Yee239432a2001-03-02 02:45:08 +0000660 path = inspect.getabsfile(object)
Zachary Wareeb432142014-07-10 11:18:00 -0500661 url = urllib.parse.quote(path)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000662 filelink = self.filelink(url, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000663 except TypeError:
664 filelink = '(built-in)'
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000665 info = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000666 if hasattr(object, '__version__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000667 version = str(object.__version__)
Ka-Ping Yee40c49912001-02-27 22:46:01 +0000668 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000669 version = version[11:-1].strip()
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000670 info.append('version %s' % self.escape(version))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000671 if hasattr(object, '__date__'):
672 info.append(self.escape(str(object.__date__)))
673 if info:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000674 head = head + ' (%s)' % ', '.join(info)
Skip Montanaro4997a692003-09-10 16:47:51 +0000675 docloc = self.getdocloc(object)
676 if docloc is not None:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000677 docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals()
Skip Montanaro4997a692003-09-10 16:47:51 +0000678 else:
679 docloc = ''
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000680 result = self.heading(
Skip Montanaro4997a692003-09-10 16:47:51 +0000681 head, '#ffffff', '#7799ee',
682 '<a href=".">index</a><br>' + filelink + docloc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000683
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000684 modules = inspect.getmembers(object, inspect.ismodule)
685
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000686 classes, cdict = [], {}
687 for key, value in inspect.getmembers(object, inspect.isclass):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +0000688 # if __all__ exists, believe it. Otherwise use old heuristic.
689 if (all is not None or
690 (inspect.getmodule(value) or object) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700691 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000692 classes.append((key, value))
693 cdict[key] = cdict[value] = '#' + key
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000694 for key, value in classes:
695 for base in value.__bases__:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000696 key, modname = base.__name__, base.__module__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000697 module = sys.modules.get(modname)
698 if modname != name and module and hasattr(module, key):
699 if getattr(module, key) is base:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000700 if not key in cdict:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000701 cdict[key] = cdict[base] = modname + '.html#' + key
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000702 funcs, fdict = [], {}
703 for key, value in inspect.getmembers(object, inspect.isroutine):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +0000704 # if __all__ exists, believe it. Otherwise use old heuristic.
705 if (all is not None or
706 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700707 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000708 funcs.append((key, value))
709 fdict[key] = '#-' + key
710 if inspect.isfunction(value): fdict[value] = fdict[key]
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000711 data = []
712 for key, value in inspect.getmembers(object, isdata):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700713 if visiblename(key, all, object):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000714 data.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000715
716 doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
717 doc = doc and '<tt>%s</tt>' % doc
Tim Peters2306d242001-09-25 03:18:32 +0000718 result = result + '<p>%s</p>\n' % doc
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000719
720 if hasattr(object, '__path__'):
721 modpkgs = []
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000722 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
723 modpkgs.append((modname, name, ispkg, 0))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000724 modpkgs.sort()
725 contents = self.multicolumn(modpkgs, self.modpkglink)
726 result = result + self.bigsection(
727 'Package Contents', '#ffffff', '#aa55cc', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000728 elif modules:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000729 contents = self.multicolumn(
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000730 modules, lambda t: self.modulelink(t[1]))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000731 result = result + self.bigsection(
Christian Heimes7131fd92008-02-19 14:21:46 +0000732 'Modules', '#ffffff', '#aa55cc', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000733
734 if classes:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000735 classlist = [value for (key, value) in classes]
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000736 contents = [
737 self.formattree(inspect.getclasstree(classlist, 1), name)]
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000738 for key, value in classes:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000739 contents.append(self.document(value, key, name, fdict, cdict))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000740 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000741 'Classes', '#ffffff', '#ee77aa', ' '.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000742 if funcs:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000743 contents = []
744 for key, value in funcs:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000745 contents.append(self.document(value, key, name, fdict, cdict))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000746 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000747 'Functions', '#ffffff', '#eeaa77', ' '.join(contents))
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000748 if data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000749 contents = []
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000750 for key, value in data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000751 contents.append(self.document(value, key))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000752 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000753 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000754 if hasattr(object, '__author__'):
755 contents = self.markup(str(object.__author__), self.preformat)
756 result = result + self.bigsection(
757 'Author', '#ffffff', '#7799ee', contents)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000758 if hasattr(object, '__credits__'):
759 contents = self.markup(str(object.__credits__), self.preformat)
760 result = result + self.bigsection(
761 'Credits', '#ffffff', '#7799ee', contents)
762
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000763 return result
764
Tim Peters8dd7ade2001-10-18 19:56:17 +0000765 def docclass(self, object, name=None, mod=None, funcs={}, classes={},
766 *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000767 """Produce HTML documentation for a class object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000768 realname = object.__name__
769 name = name or realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000770 bases = object.__bases__
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000771
Tim Petersb47879b2001-09-24 04:47:19 +0000772 contents = []
773 push = contents.append
774
Tim Petersfa26f7c2001-09-24 08:05:11 +0000775 # Cute little class to pump out a horizontal rule between sections.
776 class HorizontalRule:
777 def __init__(self):
778 self.needone = 0
779 def maybe(self):
780 if self.needone:
781 push('<hr>\n')
782 self.needone = 1
783 hr = HorizontalRule()
784
Tim Petersc86f6ca2001-09-26 21:31:51 +0000785 # List the mro, if non-trivial.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000786 mro = deque(inspect.getmro(object))
Tim Petersc86f6ca2001-09-26 21:31:51 +0000787 if len(mro) > 2:
788 hr.maybe()
789 push('<dl><dt>Method resolution order:</dt>\n')
790 for base in mro:
791 push('<dd>%s</dd>\n' % self.classlink(base,
792 object.__module__))
793 push('</dl>\n')
794
Tim Petersb47879b2001-09-24 04:47:19 +0000795 def spill(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +0000796 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000797 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000798 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000799 push(msg)
800 for name, kind, homecls, value in ok:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100801 try:
802 value = getattr(object, name)
803 except Exception:
804 # Some descriptors may meet a failure in their __get__.
805 # (bug #1785)
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +0200806 push(self.docdata(value, name, mod))
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100807 else:
808 push(self.document(value, name, mod,
809 funcs, classes, mdict, object))
Tim Petersb47879b2001-09-24 04:47:19 +0000810 push('\n')
811 return attrs
812
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000813 def spilldescriptors(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +0000814 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000815 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000816 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000817 push(msg)
818 for name, kind, homecls, value in ok:
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +0200819 push(self.docdata(value, name, mod))
Tim Petersb47879b2001-09-24 04:47:19 +0000820 return attrs
821
Tim Petersfa26f7c2001-09-24 08:05:11 +0000822 def spilldata(msg, attrs, predicate):
823 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000824 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000825 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000826 push(msg)
827 for name, kind, homecls, value in ok:
828 base = self.docother(getattr(object, name), name, mod)
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200829 if callable(value) or inspect.isdatadescriptor(value):
Guido van Rossum5e355b22002-05-21 20:56:15 +0000830 doc = getattr(value, "__doc__", None)
831 else:
832 doc = None
Tim Petersb47879b2001-09-24 04:47:19 +0000833 if doc is None:
834 push('<dl><dt>%s</dl>\n' % base)
835 else:
836 doc = self.markup(getdoc(value), self.preformat,
837 funcs, classes, mdict)
Tim Peters2306d242001-09-25 03:18:32 +0000838 doc = '<dd><tt>%s</tt>' % doc
Tim Petersb47879b2001-09-24 04:47:19 +0000839 push('<dl><dt>%s%s</dl>\n' % (base, doc))
840 push('\n')
841 return attrs
842
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000843 attrs = [(name, kind, cls, value)
844 for name, kind, cls, value in classify_class_attrs(object)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700845 if visiblename(name, obj=object)]
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000846
Tim Petersb47879b2001-09-24 04:47:19 +0000847 mdict = {}
848 for key, kind, homecls, value in attrs:
849 mdict[key] = anchor = '#' + name + '-' + key
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100850 try:
851 value = getattr(object, name)
852 except Exception:
853 # Some descriptors may meet a failure in their __get__.
854 # (bug #1785)
855 pass
Tim Petersb47879b2001-09-24 04:47:19 +0000856 try:
857 # The value may not be hashable (e.g., a data attr with
858 # a dict or list value).
859 mdict[value] = anchor
860 except TypeError:
861 pass
862
Tim Petersfa26f7c2001-09-24 08:05:11 +0000863 while attrs:
Tim Peters351e3622001-09-27 03:29:51 +0000864 if mro:
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000865 thisclass = mro.popleft()
Tim Peters351e3622001-09-27 03:29:51 +0000866 else:
867 thisclass = attrs[0][2]
Tim Petersfa26f7c2001-09-24 08:05:11 +0000868 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
869
Georg Brandl1a3284e2007-12-02 09:40:06 +0000870 if thisclass is builtins.object:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000871 attrs = inherited
872 continue
873 elif thisclass is object:
874 tag = 'defined here'
Tim Petersb47879b2001-09-24 04:47:19 +0000875 else:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000876 tag = 'inherited from %s' % self.classlink(thisclass,
877 object.__module__)
Tim Petersb47879b2001-09-24 04:47:19 +0000878 tag += ':<br>\n'
879
Raymond Hettinger95801bb2015-08-18 22:25:16 -0700880 sort_attributes(attrs, object)
Tim Petersb47879b2001-09-24 04:47:19 +0000881
882 # Pump out the attrs, segregated by kind.
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000883 attrs = spill('Methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000884 lambda t: t[1] == 'method')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000885 attrs = spill('Class methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000886 lambda t: t[1] == 'class method')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000887 attrs = spill('Static methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000888 lambda t: t[1] == 'static method')
Raymond Hettinger9dcc0952019-03-25 00:23:39 -0700889 attrs = spilldescriptors("Readonly properties %s" % tag, attrs,
Raymond Hettinger62be3382019-03-24 17:07:47 -0700890 lambda t: t[1] == 'readonly property')
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000891 attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
892 lambda t: t[1] == 'data descriptor')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000893 attrs = spilldata('Data and other attributes %s' % tag, attrs,
Tim Petersfa26f7c2001-09-24 08:05:11 +0000894 lambda t: t[1] == 'data')
Tim Petersb47879b2001-09-24 04:47:19 +0000895 assert attrs == []
Tim Peters351e3622001-09-27 03:29:51 +0000896 attrs = inherited
Tim Petersb47879b2001-09-24 04:47:19 +0000897
898 contents = ''.join(contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000899
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000900 if name == realname:
901 title = '<a name="%s">class <strong>%s</strong></a>' % (
902 name, realname)
903 else:
904 title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
905 name, name, realname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000906 if bases:
907 parents = []
908 for base in bases:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000909 parents.append(self.classlink(base, object.__module__))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000910 title = title + '(%s)' % ', '.join(parents)
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +0200911
912 decl = ''
913 try:
914 signature = inspect.signature(object)
915 except (ValueError, TypeError):
916 signature = None
917 if signature:
918 argspec = str(signature)
Serhiy Storchaka213f2292017-01-23 14:02:35 +0200919 if argspec and argspec != '()':
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +0200920 decl = name + self.escape(argspec) + '\n\n'
921
922 doc = getdoc(object)
923 if decl:
924 doc = decl + (doc or '')
925 doc = self.markup(doc, self.preformat, funcs, classes, mdict)
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000926 doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
Tim Petersc86f6ca2001-09-26 21:31:51 +0000927
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000928 return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000929
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000930 def formatvalue(self, object):
931 """Format an argument default value as text."""
Tim Peters2306d242001-09-25 03:18:32 +0000932 return self.grey('=' + self.repr(object))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000933
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000934 def docroutine(self, object, name=None, mod=None,
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000935 funcs={}, classes={}, methods={}, cl=None):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000936 """Produce HTML documentation for a function or method object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000937 realname = object.__name__
938 name = name or realname
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000939 anchor = (cl and cl.__name__ or '') + '-' + name
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000940 note = ''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000941 skipdocs = 0
Larry Hastings24a882b2014-02-20 23:34:46 -0800942 if _is_bound_method(object):
Christian Heimesff737952007-11-27 10:40:20 +0000943 imclass = object.__self__.__class__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000944 if cl:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000945 if imclass is not cl:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000946 note = ' from ' + self.classlink(imclass, mod)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000947 else:
Christian Heimesff737952007-11-27 10:40:20 +0000948 if object.__self__ is not None:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000949 note = ' method of %s instance' % self.classlink(
Christian Heimesff737952007-11-27 10:40:20 +0000950 object.__self__.__class__, mod)
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000951 else:
952 note = ' unbound %s method' % self.classlink(imclass,mod)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000953
954 if name == realname:
955 title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
956 else:
Serhiy Storchakaa44d34e2018-11-08 08:48:11 +0200957 if cl and inspect.getattr_static(cl, realname, []) is object:
Ka-Ping Yeee280c062001-03-23 14:05:53 +0000958 reallink = '<a href="#%s">%s</a>' % (
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000959 cl.__name__ + '-' + realname, realname)
960 skipdocs = 1
961 else:
962 reallink = realname
963 title = '<a name="%s"><strong>%s</strong></a> = %s' % (
964 anchor, name, reallink)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800965 argspec = None
Larry Hastings24a882b2014-02-20 23:34:46 -0800966 if inspect.isroutine(object):
Larry Hastings5c661892014-01-24 06:17:25 -0800967 try:
968 signature = inspect.signature(object)
969 except (ValueError, TypeError):
970 signature = None
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800971 if signature:
972 argspec = str(signature)
973 if realname == '<lambda>':
974 title = '<strong>%s</strong> <em>lambda</em> ' % name
975 # XXX lambda's won't usually have func_annotations['return']
976 # since the syntax doesn't support but it is possible.
977 # So removing parentheses isn't truly safe.
978 argspec = argspec[1:-1] # remove parentheses
979 if not argspec:
Tim Peters4bcfa312001-09-20 06:08:24 +0000980 argspec = '(...)'
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000981
Serhiy Storchaka66dd4aa2014-11-17 23:48:02 +0200982 decl = title + self.escape(argspec) + (note and self.grey(
Tim Peters2306d242001-09-25 03:18:32 +0000983 '<font face="helvetica, arial">%s</font>' % note))
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000984
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000985 if skipdocs:
Tim Peters2306d242001-09-25 03:18:32 +0000986 return '<dl><dt>%s</dt></dl>\n' % decl
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000987 else:
988 doc = self.markup(
989 getdoc(object), self.preformat, funcs, classes, methods)
Tim Peters2306d242001-09-25 03:18:32 +0000990 doc = doc and '<dd><tt>%s</tt></dd>' % doc
991 return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000992
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +0200993 def docdata(self, object, name=None, mod=None, cl=None):
994 """Produce html documentation for a data descriptor."""
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000995 results = []
996 push = results.append
997
998 if name:
999 push('<dl><dt><strong>%s</strong></dt>\n' % name)
Raymond Hettingera694f232019-03-27 13:16:34 -07001000 doc = self.markup(getdoc(object), self.preformat)
1001 if doc:
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001002 push('<dd><tt>%s</tt></dd>\n' % doc)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001003 push('</dl>\n')
1004
1005 return ''.join(results)
1006
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001007 docproperty = docdata
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001008
Tim Peters8dd7ade2001-10-18 19:56:17 +00001009 def docother(self, object, name=None, mod=None, *ignored):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001010 """Produce HTML documentation for a data object."""
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001011 lhs = name and '<strong>%s</strong> = ' % name or ''
1012 return lhs + self.repr(object)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001013
1014 def index(self, dir, shadowed=None):
1015 """Generate an HTML index for a directory of modules."""
1016 modpkgs = []
1017 if shadowed is None: shadowed = {}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001018 for importer, name, ispkg in pkgutil.iter_modules([dir]):
Victor Stinner4d652242011-04-12 23:41:50 +02001019 if any((0xD800 <= ord(ch) <= 0xDFFF) for ch in name):
1020 # ignore a module if its name contains a surrogate character
1021 continue
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001022 modpkgs.append((name, '', ispkg, name in shadowed))
1023 shadowed[name] = 1
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001024
1025 modpkgs.sort()
1026 contents = self.multicolumn(modpkgs, self.modpkglink)
1027 return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
1028
1029# -------------------------------------------- text documentation generator
1030
1031class TextRepr(Repr):
1032 """Class for safely making a text representation of a Python object."""
1033 def __init__(self):
1034 Repr.__init__(self)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001035 self.maxlist = self.maxtuple = 20
1036 self.maxdict = 10
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001037 self.maxstring = self.maxother = 100
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001038
1039 def repr1(self, x, level):
Skip Montanaro0fe8fce2003-06-27 15:45:41 +00001040 if hasattr(type(x), '__name__'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001041 methodname = 'repr_' + '_'.join(type(x).__name__.split())
Skip Montanaro0fe8fce2003-06-27 15:45:41 +00001042 if hasattr(self, methodname):
1043 return getattr(self, methodname)(x, level)
1044 return cram(stripid(repr(x)), self.maxother)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001045
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +00001046 def repr_string(self, x, level):
1047 test = cram(x, self.maxstring)
1048 testrepr = repr(test)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001049 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +00001050 # Backslashes are only literal in the string and are never
1051 # needed to make any special characters, so show a raw string.
1052 return 'r' + testrepr[0] + test + testrepr[0]
1053 return testrepr
1054
Skip Montanarodf708782002-03-07 22:58:02 +00001055 repr_str = repr_string
1056
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001057 def repr_instance(self, x, level):
1058 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001059 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001060 except:
1061 return '<%s instance>' % x.__class__.__name__
1062
1063class TextDoc(Doc):
1064 """Formatter class for text documentation."""
1065
1066 # ------------------------------------------- text formatting utilities
1067
1068 _repr_instance = TextRepr()
1069 repr = _repr_instance.repr
1070
1071 def bold(self, text):
1072 """Format a string in bold by overstriking."""
Georg Brandlcbd2ab12010-12-04 10:39:14 +00001073 return ''.join(ch + '\b' + ch for ch in text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001074
1075 def indent(self, text, prefix=' '):
1076 """Indent text by prepending a given prefix to each line."""
1077 if not text: return ''
Collin Winter72e110c2007-07-17 00:27:30 +00001078 lines = [prefix + line for line in text.split('\n')]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001079 if lines: lines[-1] = lines[-1].rstrip()
1080 return '\n'.join(lines)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001081
1082 def section(self, title, contents):
1083 """Format a section with a given heading."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001084 clean_contents = self.indent(contents).rstrip()
1085 return self.bold(title) + '\n' + clean_contents + '\n\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001086
1087 # ---------------------------------------------- type-specific routines
1088
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001089 def formattree(self, tree, modname, parent=None, prefix=''):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001090 """Render in text a class tree as returned by inspect.getclasstree()."""
1091 result = ''
1092 for entry in tree:
1093 if type(entry) is type(()):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001094 c, bases = entry
1095 result = result + prefix + classname(c, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001096 if bases and bases != (parent,):
Georg Brandlcbd2ab12010-12-04 10:39:14 +00001097 parents = (classname(c, modname) for c in bases)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001098 result = result + '(%s)' % ', '.join(parents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001099 result = result + '\n'
1100 elif type(entry) is type([]):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001101 result = result + self.formattree(
1102 entry, modname, c, prefix + ' ')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001103 return result
1104
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001105 def docmodule(self, object, name=None, mod=None):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001106 """Produce text documentation for a given module object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001107 name = object.__name__ # ignore the passed-in name
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001108 synop, desc = splitdoc(getdoc(object))
1109 result = self.section('NAME', name + (synop and ' - ' + synop))
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001110 all = getattr(object, '__all__', None)
Skip Montanaro4997a692003-09-10 16:47:51 +00001111 docloc = self.getdocloc(object)
1112 if docloc is not None:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001113 result = result + self.section('MODULE REFERENCE', docloc + """
1114
Éric Araujo647ef8c2011-09-11 00:43:20 +02001115The following documentation is automatically generated from the Python
1116source files. It may be incomplete, incorrect or include features that
1117are considered implementation detail and may vary between Python
1118implementations. When in doubt, consult the module reference at the
1119location listed above.
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001120""")
Skip Montanaro4997a692003-09-10 16:47:51 +00001121
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001122 if desc:
1123 result = result + self.section('DESCRIPTION', desc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001124
1125 classes = []
1126 for key, value in inspect.getmembers(object, inspect.isclass):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +00001127 # if __all__ exists, believe it. Otherwise use old heuristic.
1128 if (all is not None
1129 or (inspect.getmodule(value) or object) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001130 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001131 classes.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001132 funcs = []
1133 for key, value in inspect.getmembers(object, inspect.isroutine):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +00001134 # if __all__ exists, believe it. Otherwise use old heuristic.
1135 if (all is not None or
1136 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001137 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001138 funcs.append((key, value))
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001139 data = []
1140 for key, value in inspect.getmembers(object, isdata):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001141 if visiblename(key, all, object):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001142 data.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001143
Christian Heimes1af737c2008-01-23 08:24:23 +00001144 modpkgs = []
1145 modpkgs_names = set()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001146 if hasattr(object, '__path__'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001147 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
Christian Heimes1af737c2008-01-23 08:24:23 +00001148 modpkgs_names.add(modname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001149 if ispkg:
1150 modpkgs.append(modname + ' (package)')
1151 else:
1152 modpkgs.append(modname)
1153
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001154 modpkgs.sort()
1155 result = result + self.section(
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001156 'PACKAGE CONTENTS', '\n'.join(modpkgs))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001157
Christian Heimes1af737c2008-01-23 08:24:23 +00001158 # Detect submodules as sometimes created by C extensions
1159 submodules = []
1160 for key, value in inspect.getmembers(object, inspect.ismodule):
1161 if value.__name__.startswith(name + '.') and key not in modpkgs_names:
1162 submodules.append(key)
1163 if submodules:
1164 submodules.sort()
1165 result = result + self.section(
Amaury Forgeot d'Arc768db922008-04-24 21:00:04 +00001166 'SUBMODULES', '\n'.join(submodules))
Christian Heimes1af737c2008-01-23 08:24:23 +00001167
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001168 if classes:
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001169 classlist = [value for key, value in classes]
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001170 contents = [self.formattree(
1171 inspect.getclasstree(classlist, 1), name)]
1172 for key, value in classes:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001173 contents.append(self.document(value, key, name))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001174 result = result + self.section('CLASSES', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001175
1176 if funcs:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001177 contents = []
1178 for key, value in funcs:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001179 contents.append(self.document(value, key, name))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001180 result = result + self.section('FUNCTIONS', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001181
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001182 if data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001183 contents = []
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001184 for key, value in data:
Georg Brandl8b813db2005-10-01 16:32:31 +00001185 contents.append(self.docother(value, key, name, maxlen=70))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001186 result = result + self.section('DATA', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001187
1188 if hasattr(object, '__version__'):
1189 version = str(object.__version__)
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001190 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001191 version = version[11:-1].strip()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001192 result = result + self.section('VERSION', version)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +00001193 if hasattr(object, '__date__'):
1194 result = result + self.section('DATE', str(object.__date__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001195 if hasattr(object, '__author__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +00001196 result = result + self.section('AUTHOR', str(object.__author__))
1197 if hasattr(object, '__credits__'):
1198 result = result + self.section('CREDITS', str(object.__credits__))
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001199 try:
1200 file = inspect.getabsfile(object)
1201 except TypeError:
1202 file = '(built-in)'
1203 result = result + self.section('FILE', file)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001204 return result
1205
Georg Brandl9bd45f992010-12-03 09:58:38 +00001206 def docclass(self, object, name=None, mod=None, *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001207 """Produce text documentation for a given class object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001208 realname = object.__name__
1209 name = name or realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001210 bases = object.__bases__
1211
Tim Petersc86f6ca2001-09-26 21:31:51 +00001212 def makename(c, m=object.__module__):
1213 return classname(c, m)
1214
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001215 if name == realname:
1216 title = 'class ' + self.bold(realname)
1217 else:
1218 title = self.bold(name) + ' = class ' + realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001219 if bases:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001220 parents = map(makename, bases)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001221 title = title + '(%s)' % ', '.join(parents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001222
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +02001223 contents = []
Tim Peters28355492001-09-23 21:29:55 +00001224 push = contents.append
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001225
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +02001226 try:
1227 signature = inspect.signature(object)
1228 except (ValueError, TypeError):
1229 signature = None
1230 if signature:
1231 argspec = str(signature)
Serhiy Storchaka213f2292017-01-23 14:02:35 +02001232 if argspec and argspec != '()':
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +02001233 push(name + argspec + '\n')
1234
1235 doc = getdoc(object)
1236 if doc:
1237 push(doc + '\n')
1238
Tim Petersc86f6ca2001-09-26 21:31:51 +00001239 # List the mro, if non-trivial.
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001240 mro = deque(inspect.getmro(object))
Tim Petersc86f6ca2001-09-26 21:31:51 +00001241 if len(mro) > 2:
1242 push("Method resolution order:")
1243 for base in mro:
1244 push(' ' + makename(base))
1245 push('')
1246
Sanyam Khuranaa323cdc2018-10-21 00:22:02 -07001247 # List the built-in subclasses, if any:
1248 subclasses = sorted(
Sanyam Khuranab539cef2018-12-31 10:44:47 +05301249 (str(cls.__name__) for cls in type.__subclasses__(object)
Sanyam Khuranaa323cdc2018-10-21 00:22:02 -07001250 if not cls.__name__.startswith("_") and cls.__module__ == "builtins"),
1251 key=str.lower
1252 )
1253 no_of_subclasses = len(subclasses)
1254 MAX_SUBCLASSES_TO_DISPLAY = 4
1255 if subclasses:
1256 push("Built-in subclasses:")
1257 for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:
1258 push(' ' + subclassname)
1259 if no_of_subclasses > MAX_SUBCLASSES_TO_DISPLAY:
1260 push(' ... and ' +
1261 str(no_of_subclasses - MAX_SUBCLASSES_TO_DISPLAY) +
1262 ' other subclasses')
1263 push('')
1264
Tim Petersf4aad8e2001-09-24 22:40:47 +00001265 # Cute little class to pump out a horizontal rule between sections.
1266 class HorizontalRule:
1267 def __init__(self):
1268 self.needone = 0
1269 def maybe(self):
1270 if self.needone:
1271 push('-' * 70)
1272 self.needone = 1
1273 hr = HorizontalRule()
1274
Tim Peters28355492001-09-23 21:29:55 +00001275 def spill(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +00001276 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001277 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001278 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001279 push(msg)
1280 for name, kind, homecls, value in ok:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +01001281 try:
1282 value = getattr(object, name)
1283 except Exception:
1284 # Some descriptors may meet a failure in their __get__.
1285 # (bug #1785)
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001286 push(self.docdata(value, name, mod))
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +01001287 else:
1288 push(self.document(value,
1289 name, mod, object))
Tim Peters28355492001-09-23 21:29:55 +00001290 return attrs
1291
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001292 def spilldescriptors(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +00001293 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001294 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001295 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001296 push(msg)
1297 for name, kind, homecls, value in ok:
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001298 push(self.docdata(value, name, mod))
Tim Peters28355492001-09-23 21:29:55 +00001299 return attrs
Tim Petersb47879b2001-09-24 04:47:19 +00001300
Tim Petersfa26f7c2001-09-24 08:05:11 +00001301 def spilldata(msg, attrs, predicate):
1302 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001303 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001304 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001305 push(msg)
1306 for name, kind, homecls, value in ok:
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001307 if callable(value) or inspect.isdatadescriptor(value):
Ka-Ping Yeebba6acc2005-02-19 22:58:26 +00001308 doc = getdoc(value)
Guido van Rossum5e355b22002-05-21 20:56:15 +00001309 else:
1310 doc = None
Serhiy Storchaka056eb022014-02-19 23:05:12 +02001311 try:
1312 obj = getattr(object, name)
1313 except AttributeError:
1314 obj = homecls.__dict__[name]
1315 push(self.docother(obj, name, mod, maxlen=70, doc=doc) +
1316 '\n')
Tim Peters28355492001-09-23 21:29:55 +00001317 return attrs
1318
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001319 attrs = [(name, kind, cls, value)
1320 for name, kind, cls, value in classify_class_attrs(object)
Raymond Hettinger1103d052011-03-25 14:15:24 -07001321 if visiblename(name, obj=object)]
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001322
Tim Petersfa26f7c2001-09-24 08:05:11 +00001323 while attrs:
Tim Peters351e3622001-09-27 03:29:51 +00001324 if mro:
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001325 thisclass = mro.popleft()
Tim Peters351e3622001-09-27 03:29:51 +00001326 else:
1327 thisclass = attrs[0][2]
Tim Petersfa26f7c2001-09-24 08:05:11 +00001328 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
1329
Georg Brandl1a3284e2007-12-02 09:40:06 +00001330 if thisclass is builtins.object:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001331 attrs = inherited
1332 continue
1333 elif thisclass is object:
Tim Peters28355492001-09-23 21:29:55 +00001334 tag = "defined here"
1335 else:
Tim Petersfa26f7c2001-09-24 08:05:11 +00001336 tag = "inherited from %s" % classname(thisclass,
1337 object.__module__)
Raymond Hettinger95801bb2015-08-18 22:25:16 -07001338
1339 sort_attributes(attrs, object)
Tim Peters28355492001-09-23 21:29:55 +00001340
1341 # Pump out the attrs, segregated by kind.
Tim Petersf4aad8e2001-09-24 22:40:47 +00001342 attrs = spill("Methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001343 lambda t: t[1] == 'method')
Tim Petersf4aad8e2001-09-24 22:40:47 +00001344 attrs = spill("Class methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001345 lambda t: t[1] == 'class method')
Tim Petersf4aad8e2001-09-24 22:40:47 +00001346 attrs = spill("Static methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001347 lambda t: t[1] == 'static method')
Raymond Hettinger62be3382019-03-24 17:07:47 -07001348 attrs = spilldescriptors("Readonly properties %s:\n" % tag, attrs,
1349 lambda t: t[1] == 'readonly property')
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001350 attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
1351 lambda t: t[1] == 'data descriptor')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001352 attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
1353 lambda t: t[1] == 'data')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001354
Tim Peters28355492001-09-23 21:29:55 +00001355 assert attrs == []
Tim Peters351e3622001-09-27 03:29:51 +00001356 attrs = inherited
Tim Peters28355492001-09-23 21:29:55 +00001357
1358 contents = '\n'.join(contents)
1359 if not contents:
1360 return title + '\n'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001361 return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001362
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001363 def formatvalue(self, object):
1364 """Format an argument default value as text."""
1365 return '=' + self.repr(object)
1366
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001367 def docroutine(self, object, name=None, mod=None, cl=None):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001368 """Produce text documentation for a function or method object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001369 realname = object.__name__
1370 name = name or realname
1371 note = ''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001372 skipdocs = 0
Larry Hastings24a882b2014-02-20 23:34:46 -08001373 if _is_bound_method(object):
Christian Heimesff737952007-11-27 10:40:20 +00001374 imclass = object.__self__.__class__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001375 if cl:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001376 if imclass is not cl:
1377 note = ' from ' + classname(imclass, mod)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001378 else:
Christian Heimesff737952007-11-27 10:40:20 +00001379 if object.__self__ is not None:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +00001380 note = ' method of %s instance' % classname(
Christian Heimesff737952007-11-27 10:40:20 +00001381 object.__self__.__class__, mod)
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +00001382 else:
1383 note = ' unbound %s method' % classname(imclass,mod)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001384
1385 if name == realname:
1386 title = self.bold(realname)
1387 else:
Serhiy Storchakaa44d34e2018-11-08 08:48:11 +02001388 if cl and inspect.getattr_static(cl, realname, []) is object:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001389 skipdocs = 1
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001390 title = self.bold(name) + ' = ' + realname
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001391 argspec = None
Larry Hastings5c661892014-01-24 06:17:25 -08001392
1393 if inspect.isroutine(object):
1394 try:
1395 signature = inspect.signature(object)
1396 except (ValueError, TypeError):
1397 signature = None
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001398 if signature:
1399 argspec = str(signature)
1400 if realname == '<lambda>':
1401 title = self.bold(name) + ' lambda '
1402 # XXX lambda's won't usually have func_annotations['return']
1403 # since the syntax doesn't support but it is possible.
1404 # So removing parentheses isn't truly safe.
1405 argspec = argspec[1:-1] # remove parentheses
1406 if not argspec:
Tim Peters4bcfa312001-09-20 06:08:24 +00001407 argspec = '(...)'
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001408 decl = title + argspec + note
1409
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001410 if skipdocs:
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001411 return decl + '\n'
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001412 else:
1413 doc = getdoc(object) or ''
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001414 return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001415
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001416 def docdata(self, object, name=None, mod=None, cl=None):
1417 """Produce text documentation for a data descriptor."""
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001418 results = []
1419 push = results.append
1420
1421 if name:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001422 push(self.bold(name))
1423 push('\n')
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001424 doc = getdoc(object) or ''
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001425 if doc:
1426 push(self.indent(doc))
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001427 push('\n')
1428 return ''.join(results)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001429
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001430 docproperty = docdata
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001431
Georg Brandl8b813db2005-10-01 16:32:31 +00001432 def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001433 """Produce text documentation for a data object."""
1434 repr = self.repr(object)
1435 if maxlen:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001436 line = (name and name + ' = ' or '') + repr
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001437 chop = maxlen - len(line)
1438 if chop < 0: repr = repr[:chop] + '...'
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001439 line = (name and self.bold(name) + ' = ' or '') + repr
Tim Peters28355492001-09-23 21:29:55 +00001440 if doc is not None:
1441 line += '\n' + self.indent(str(doc))
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001442 return line
1443
Georg Brandld80d5f42010-12-03 07:47:22 +00001444class _PlainTextDoc(TextDoc):
1445 """Subclass of TextDoc which overrides string styling"""
1446 def bold(self, text):
1447 return text
1448
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001449# --------------------------------------------------------- user interfaces
1450
1451def pager(text):
1452 """The first time this is called, determine what kind of pager to use."""
1453 global pager
1454 pager = getpager()
1455 pager(text)
1456
1457def getpager():
1458 """Decide what method to use for paging through text."""
Benjamin Peterson159824e2014-06-07 20:14:26 -07001459 if not hasattr(sys.stdin, "isatty"):
1460 return plainpager
Guido van Rossuma01a8b62007-05-27 09:20:14 +00001461 if not hasattr(sys.stdout, "isatty"):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001462 return plainpager
1463 if not sys.stdin.isatty() or not sys.stdout.isatty():
1464 return plainpager
doko@ubuntu.com96575452016-06-14 08:39:31 +02001465 use_pager = os.environ.get('MANPAGER') or os.environ.get('PAGER')
1466 if use_pager:
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001467 if sys.platform == 'win32': # pipes completely broken in Windows
doko@ubuntu.comc8fd1922016-06-14 09:03:52 +02001468 return lambda text: tempfilepager(plain(text), use_pager)
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001469 elif os.environ.get('TERM') in ('dumb', 'emacs'):
doko@ubuntu.comc8fd1922016-06-14 09:03:52 +02001470 return lambda text: pipepager(plain(text), use_pager)
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001471 else:
doko@ubuntu.comc8fd1922016-06-14 09:03:52 +02001472 return lambda text: pipepager(text, use_pager)
Ka-Ping Yeea487e4e2005-11-05 04:49:18 +00001473 if os.environ.get('TERM') in ('dumb', 'emacs'):
1474 return plainpager
Jesus Cea4791a242012-10-05 03:15:39 +02001475 if sys.platform == 'win32':
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001476 return lambda text: tempfilepager(plain(text), 'more <')
Skip Montanarod404bee2002-09-26 21:44:57 +00001477 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001478 return lambda text: pipepager(text, 'less')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001479
1480 import tempfile
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001481 (fd, filename) = tempfile.mkstemp()
1482 os.close(fd)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001483 try:
Georg Brandl3dbca812008-07-23 16:10:53 +00001484 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001485 return lambda text: pipepager(text, 'more')
1486 else:
1487 return ttypager
1488 finally:
1489 os.unlink(filename)
1490
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001491def plain(text):
1492 """Remove boldface formatting from text."""
1493 return re.sub('.\b', '', text)
1494
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001495def pipepager(text, cmd):
1496 """Page through text by feeding it to another program."""
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001497 import subprocess
1498 proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001499 try:
R David Murray1058cda2015-03-29 15:15:40 -04001500 with io.TextIOWrapper(proc.stdin, errors='backslashreplace') as pipe:
R David Murraye7f5e142015-03-30 10:14:47 -04001501 try:
1502 pipe.write(text)
1503 except KeyboardInterrupt:
1504 # We've hereby abandoned whatever text hasn't been written,
1505 # but the pager is still in control of the terminal.
1506 pass
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001507 except OSError:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001508 pass # Ignore broken pipes caused by quitting the pager program.
R David Murray1058cda2015-03-29 15:15:40 -04001509 while True:
1510 try:
1511 proc.wait()
1512 break
1513 except KeyboardInterrupt:
1514 # Ignore ctl-c like the pager itself does. Otherwise the pager is
1515 # left running and the terminal is in raw mode and unusable.
1516 pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001517
1518def tempfilepager(text, cmd):
1519 """Page through text by invoking a program on a temporary file."""
1520 import tempfile
Tim Peters550e4e52003-02-07 01:53:46 +00001521 filename = tempfile.mktemp()
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001522 with open(filename, 'w', errors='backslashreplace') as file:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01001523 file.write(text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001524 try:
Georg Brandl3dbca812008-07-23 16:10:53 +00001525 os.system(cmd + ' "' + filename + '"')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001526 finally:
1527 os.unlink(filename)
1528
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001529def _escape_stdout(text):
1530 # Escape non-encodable characters to avoid encoding errors later
1531 encoding = getattr(sys.stdout, 'encoding', None) or 'utf-8'
1532 return text.encode(encoding, 'backslashreplace').decode(encoding)
1533
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001534def ttypager(text):
1535 """Page through text on a text terminal."""
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001536 lines = plain(_escape_stdout(text)).split('\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001537 try:
1538 import tty
1539 fd = sys.stdin.fileno()
1540 old = tty.tcgetattr(fd)
1541 tty.setcbreak(fd)
1542 getchar = lambda: sys.stdin.read(1)
Serhiy Storchakaab5e9b92014-11-28 00:09:29 +02001543 except (ImportError, AttributeError, io.UnsupportedOperation):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001544 tty = None
1545 getchar = lambda: sys.stdin.readline()[:-1][:1]
1546
1547 try:
Serhiy Storchakaab5e9b92014-11-28 00:09:29 +02001548 try:
1549 h = int(os.environ.get('LINES', 0))
1550 except ValueError:
1551 h = 0
1552 if h <= 1:
1553 h = 25
1554 r = inc = h - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001555 sys.stdout.write('\n'.join(lines[:inc]) + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001556 while lines[r:]:
1557 sys.stdout.write('-- more --')
1558 sys.stdout.flush()
1559 c = getchar()
1560
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001561 if c in ('q', 'Q'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001562 sys.stdout.write('\r \r')
1563 break
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001564 elif c in ('\r', '\n'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001565 sys.stdout.write('\r \r' + lines[r] + '\n')
1566 r = r + 1
1567 continue
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001568 if c in ('b', 'B', '\x1b'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001569 r = r - inc - inc
1570 if r < 0: r = 0
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001571 sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001572 r = r + inc
1573
1574 finally:
1575 if tty:
1576 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
1577
1578def plainpager(text):
1579 """Simply print unformatted text. This is the ultimate fallback."""
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001580 sys.stdout.write(plain(_escape_stdout(text)))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001581
1582def describe(thing):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001583 """Produce a short description of the given thing."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001584 if inspect.ismodule(thing):
1585 if thing.__name__ in sys.builtin_module_names:
1586 return 'built-in module ' + thing.__name__
1587 if hasattr(thing, '__path__'):
1588 return 'package ' + thing.__name__
1589 else:
1590 return 'module ' + thing.__name__
1591 if inspect.isbuiltin(thing):
1592 return 'built-in function ' + thing.__name__
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001593 if inspect.isgetsetdescriptor(thing):
1594 return 'getset descriptor %s.%s.%s' % (
1595 thing.__objclass__.__module__, thing.__objclass__.__name__,
1596 thing.__name__)
1597 if inspect.ismemberdescriptor(thing):
1598 return 'member descriptor %s.%s.%s' % (
1599 thing.__objclass__.__module__, thing.__objclass__.__name__,
1600 thing.__name__)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001601 if inspect.isclass(thing):
1602 return 'class ' + thing.__name__
1603 if inspect.isfunction(thing):
1604 return 'function ' + thing.__name__
1605 if inspect.ismethod(thing):
1606 return 'method ' + thing.__name__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001607 return type(thing).__name__
1608
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001609def locate(path, forceload=0):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001610 """Locate an object by name or dotted path, importing as necessary."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001611 parts = [part for part in path.split('.') if part]
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001612 module, n = None, 0
1613 while n < len(parts):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001614 nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001615 if nextmodule: module, n = nextmodule, n + 1
1616 else: break
1617 if module:
1618 object = module
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001619 else:
Éric Araujoe64e51b2011-07-29 17:03:55 +02001620 object = builtins
1621 for part in parts[n:]:
1622 try:
1623 object = getattr(object, part)
1624 except AttributeError:
1625 return None
1626 return object
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001627
1628# --------------------------------------- interactive interpreter interface
1629
1630text = TextDoc()
Georg Brandld80d5f42010-12-03 07:47:22 +00001631plaintext = _PlainTextDoc()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001632html = HTMLDoc()
1633
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001634def resolve(thing, forceload=0):
1635 """Given an object or a path to an object, get the object and its name."""
1636 if isinstance(thing, str):
1637 object = locate(thing, forceload)
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001638 if object is None:
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001639 raise ImportError('''\
1640No Python documentation found for %r.
1641Use help() to get the interactive help utility.
1642Use help(str) for help on the str class.''' % thing)
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001643 return object, thing
1644 else:
R David Murrayc43125a2012-04-23 13:23:57 -04001645 name = getattr(thing, '__name__', None)
1646 return thing, name if isinstance(name, str) else None
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001647
Georg Brandld80d5f42010-12-03 07:47:22 +00001648def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
1649 renderer=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650 """Render text documentation, given an object or a path to an object."""
Georg Brandld80d5f42010-12-03 07:47:22 +00001651 if renderer is None:
1652 renderer = text
Guido van Rossumd8faa362007-04-27 19:54:29 +00001653 object, name = resolve(thing, forceload)
1654 desc = describe(object)
1655 module = inspect.getmodule(object)
1656 if name and '.' in name:
1657 desc += ' in ' + name[:name.rfind('.')]
1658 elif module and module is not object:
1659 desc += ' in module ' + module.__name__
Amaury Forgeot d'Arc768db922008-04-24 21:00:04 +00001660
1661 if not (inspect.ismodule(object) or
Guido van Rossumd8faa362007-04-27 19:54:29 +00001662 inspect.isclass(object) or
1663 inspect.isroutine(object) or
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001664 inspect.isdatadescriptor(object)):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001665 # If the passed object is a piece of data or an instance,
1666 # document its available methods instead of its value.
1667 object = type(object)
1668 desc += ' object'
Georg Brandld80d5f42010-12-03 07:47:22 +00001669 return title % desc + '\n\n' + renderer.document(object, name)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001670
Georg Brandld80d5f42010-12-03 07:47:22 +00001671def doc(thing, title='Python Library Documentation: %s', forceload=0,
1672 output=None):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001673 """Display text documentation, given an object or a path to an object."""
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001674 try:
Georg Brandld80d5f42010-12-03 07:47:22 +00001675 if output is None:
1676 pager(render_doc(thing, title, forceload))
1677 else:
1678 output.write(render_doc(thing, title, forceload, plaintext))
Guido van Rossumb940e112007-01-10 16:19:56 +00001679 except (ImportError, ErrorDuringImport) as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001680 print(value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001681
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001682def writedoc(thing, forceload=0):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001683 """Write HTML documentation to a file in the current directory."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001684 try:
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001685 object, name = resolve(thing, forceload)
1686 page = html.page(describe(object), html.document(object, name))
Serhiy Storchaka46ba6c82015-04-04 11:01:02 +03001687 with open(name + '.html', 'w', encoding='utf-8') as file:
1688 file.write(page)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001689 print('wrote', name + '.html')
Guido van Rossumb940e112007-01-10 16:19:56 +00001690 except (ImportError, ErrorDuringImport) as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001691 print(value)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001692
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001693def writedocs(dir, pkgpath='', done=None):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001694 """Write out HTML documentation for all modules in a directory tree."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001695 if done is None: done = {}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001696 for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
1697 writedoc(modname)
1698 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001699
1700class Helper:
Georg Brandl6b38daa2008-06-01 21:05:17 +00001701
1702 # These dictionaries map a topic name to either an alias, or a tuple
1703 # (label, seealso-items). The "label" is the label of the corresponding
1704 # section in the .rst file under Doc/ and an index into the dictionary
Georg Brandl5617db82009-04-27 16:28:57 +00001705 # in pydoc_data/topics.py.
Georg Brandl6b38daa2008-06-01 21:05:17 +00001706 #
1707 # CAUTION: if you change one of these dictionaries, be sure to adapt the
Jelle Zijlstraac317702017-10-05 20:24:46 -07001708 # list of needed labels in Doc/tools/extensions/pyspecific.py and
Georg Brandl5617db82009-04-27 16:28:57 +00001709 # regenerate the pydoc_data/topics.py file by running
Georg Brandl6b38daa2008-06-01 21:05:17 +00001710 # make pydoc-topics
1711 # in Doc/ and copying the output file into the Lib/ directory.
1712
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001713 keywords = {
Ezio Melottib185a042011-04-28 07:42:55 +03001714 'False': '',
1715 'None': '',
1716 'True': '',
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001717 'and': 'BOOLEAN',
Guido van Rossumd8faa362007-04-27 19:54:29 +00001718 'as': 'with',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001719 'assert': ('assert', ''),
Jelle Zijlstraac317702017-10-05 20:24:46 -07001720 'async': ('async', ''),
1721 'await': ('await', ''),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001722 'break': ('break', 'while for'),
1723 'class': ('class', 'CLASSES SPECIALMETHODS'),
1724 'continue': ('continue', 'while for'),
1725 'def': ('function', ''),
1726 'del': ('del', 'BASICMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001727 'elif': 'if',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001728 'else': ('else', 'while for'),
Georg Brandl0d855392008-08-30 19:53:05 +00001729 'except': 'try',
1730 'finally': 'try',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001731 'for': ('for', 'break continue while'),
Georg Brandl0d855392008-08-30 19:53:05 +00001732 'from': 'import',
Georg Brandl74abf6f2010-11-20 19:54:36 +00001733 'global': ('global', 'nonlocal NAMESPACES'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001734 'if': ('if', 'TRUTHVALUE'),
1735 'import': ('import', 'MODULES'),
Georg Brandl395ed242009-09-04 08:07:32 +00001736 'in': ('in', 'SEQUENCEMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001737 'is': 'COMPARISON',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001738 'lambda': ('lambda', 'FUNCTIONS'),
Georg Brandl74abf6f2010-11-20 19:54:36 +00001739 'nonlocal': ('nonlocal', 'global NAMESPACES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001740 'not': 'BOOLEAN',
1741 'or': 'BOOLEAN',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001742 'pass': ('pass', ''),
1743 'raise': ('raise', 'EXCEPTIONS'),
1744 'return': ('return', 'FUNCTIONS'),
1745 'try': ('try', 'EXCEPTIONS'),
1746 'while': ('while', 'break continue if TRUTHVALUE'),
1747 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
1748 'yield': ('yield', ''),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001749 }
Georg Brandldb7b6b92009-01-01 15:53:14 +00001750 # Either add symbols to this dictionary or to the symbols dictionary
1751 # directly: Whichever is easier. They are merged later.
Andrés Delfinob2043bb2018-05-05 13:07:32 -03001752 _strprefixes = [p + q for p in ('b', 'f', 'r', 'u') for q in ("'", '"')]
Georg Brandldb7b6b92009-01-01 15:53:14 +00001753 _symbols_inverse = {
Andrés Delfinob2043bb2018-05-05 13:07:32 -03001754 'STRINGS' : ("'", "'''", '"', '"""', *_strprefixes),
Georg Brandldb7b6b92009-01-01 15:53:14 +00001755 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
1756 '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
1757 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
1758 'UNARY' : ('-', '~'),
1759 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
1760 '^=', '<<=', '>>=', '**=', '//='),
1761 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
1762 'COMPLEX' : ('j', 'J')
1763 }
1764 symbols = {
1765 '%': 'OPERATORS FORMATTING',
1766 '**': 'POWER',
1767 ',': 'TUPLES LISTS FUNCTIONS',
1768 '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
1769 '...': 'ELLIPSIS',
1770 ':': 'SLICINGS DICTIONARYLITERALS',
1771 '@': 'def class',
1772 '\\': 'STRINGS',
1773 '_': 'PRIVATENAMES',
1774 '__': 'PRIVATENAMES SPECIALMETHODS',
1775 '`': 'BACKQUOTES',
1776 '(': 'TUPLES FUNCTIONS CALLS',
1777 ')': 'TUPLES FUNCTIONS CALLS',
1778 '[': 'LISTS SUBSCRIPTS SLICINGS',
1779 ']': 'LISTS SUBSCRIPTS SLICINGS'
1780 }
1781 for topic, symbols_ in _symbols_inverse.items():
1782 for symbol in symbols_:
1783 topics = symbols.get(symbol, topic)
1784 if topic not in topics:
1785 topics = topics + ' ' + topic
1786 symbols[symbol] = topics
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001787
1788 topics = {
Georg Brandl6b38daa2008-06-01 21:05:17 +00001789 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
1790 'FUNCTIONS CLASSES MODULES FILES inspect'),
1791 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS '
1792 'FORMATTING TYPES'),
1793 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
1794 'FORMATTING': ('formatstrings', 'OPERATORS'),
1795 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
1796 'FORMATTING TYPES'),
1797 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
1798 'INTEGER': ('integers', 'int range'),
1799 'FLOAT': ('floating', 'float math'),
1800 'COMPLEX': ('imaginary', 'complex cmath'),
1801 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001802 'MAPPINGS': 'DICTIONARIES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001803 'FUNCTIONS': ('typesfunctions', 'def TYPES'),
1804 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
1805 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
1806 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001807 'FRAMEOBJECTS': 'TYPES',
1808 'TRACEBACKS': 'TYPES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001809 'NONE': ('bltin-null-object', ''),
1810 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001811 'SPECIALATTRIBUTES': ('specialattrs', ''),
1812 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
1813 'MODULES': ('typesmodules', 'import'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001814 'PACKAGES': 'import',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001815 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
1816 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
1817 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
1818 'LISTS DICTIONARIES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001819 'OPERATORS': 'EXPRESSIONS',
1820 'PRECEDENCE': 'EXPRESSIONS',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001821 'OBJECTS': ('objects', 'TYPES'),
1822 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
Georg Brandl395ed242009-09-04 08:07:32 +00001823 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '
1824 'NUMBERMETHODS CLASSES'),
Mark Dickinsona56c4672009-01-27 18:17:45 +00001825 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001826 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
1827 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
Georg Brandl395ed242009-09-04 08:07:32 +00001828 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS '
Georg Brandl6b38daa2008-06-01 21:05:17 +00001829 'SPECIALMETHODS'),
1830 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
1831 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
1832 'SPECIALMETHODS'),
1833 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
Georg Brandl74abf6f2010-11-20 19:54:36 +00001834 'NAMESPACES': ('naming', 'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001835 'DYNAMICFEATURES': ('dynamic-features', ''),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001836 'SCOPING': 'NAMESPACES',
1837 'FRAMES': 'NAMESPACES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001838 'EXCEPTIONS': ('exceptions', 'try except finally raise'),
1839 'CONVERSIONS': ('conversions', ''),
1840 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
1841 'SPECIALIDENTIFIERS': ('id-classes', ''),
1842 'PRIVATENAMES': ('atom-identifiers', ''),
1843 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS '
1844 'LISTLITERALS DICTIONARYLITERALS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001845 'TUPLES': 'SEQUENCES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001846 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
1847 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
1848 'LISTLITERALS': ('lists', 'LISTS LITERALS'),
1849 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
1850 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
1851 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
Georg Brandl395ed242009-09-04 08:07:32 +00001852 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'),
1853 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001854 'CALLS': ('calls', 'EXPRESSIONS'),
1855 'POWER': ('power', 'EXPRESSIONS'),
1856 'UNARY': ('unary', 'EXPRESSIONS'),
1857 'BINARY': ('binary', 'EXPRESSIONS'),
1858 'SHIFTING': ('shifting', 'EXPRESSIONS'),
1859 'BITWISE': ('bitwise', 'EXPRESSIONS'),
1860 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
1861 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001862 'ASSERTION': 'assert',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001863 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
1864 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001865 'DELETION': 'del',
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001866 'RETURNING': 'return',
1867 'IMPORTING': 'import',
1868 'CONDITIONAL': 'if',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001869 'LOOPING': ('compound', 'for while break continue'),
1870 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
1871 'DEBUGGING': ('debugger', 'pdb'),
1872 'CONTEXTMANAGERS': ('context-managers', 'with'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001873 }
1874
Georg Brandl78aa3962010-07-31 21:51:48 +00001875 def __init__(self, input=None, output=None):
1876 self._input = input
1877 self._output = output
1878
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001879 @property
1880 def input(self):
1881 return self._input or sys.stdin
1882
1883 @property
1884 def output(self):
1885 return self._output or sys.stdout
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001886
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001887 def __repr__(self):
Ka-Ping Yee9bc576b2001-04-13 13:57:31 +00001888 if inspect.stack()[1][3] == '?':
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001889 self()
1890 return ''
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03001891 return '<%s.%s instance>' % (self.__class__.__module__,
1892 self.__class__.__qualname__)
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001893
Alexander Belopolsky2e733c92010-07-04 17:00:20 +00001894 _GoInteractive = object()
1895 def __call__(self, request=_GoInteractive):
1896 if request is not self._GoInteractive:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001897 self.help(request)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001898 else:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001899 self.intro()
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001900 self.interact()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001901 self.output.write('''
Fred Drakee61967f2001-05-10 18:41:02 +00001902You are now leaving help and returning to the Python interpreter.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001903If you want to ask for help on a particular object directly from the
1904interpreter, you can type "help(object)". Executing "help('string')"
1905has the same effect as typing a particular string at the help> prompt.
1906''')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001907
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001908 def interact(self):
1909 self.output.write('\n')
Guido van Rossum8ca162f2002-04-07 06:36:23 +00001910 while True:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001911 try:
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001912 request = self.getline('help> ')
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001913 if not request: break
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001914 except (KeyboardInterrupt, EOFError):
1915 break
Andrés Delfinob2043bb2018-05-05 13:07:32 -03001916 request = request.strip()
1917
1918 # Make sure significant trailing quoting marks of literals don't
1919 # get deleted while cleaning input
1920 if (len(request) > 2 and request[0] == request[-1] in ("'", '"')
1921 and request[0] not in request[1:-1]):
1922 request = request[1:-1]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001923 if request.lower() in ('q', 'quit'): break
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001924 if request == 'help':
1925 self.intro()
1926 else:
1927 self.help(request)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001928
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001929 def getline(self, prompt):
Guido van Rossum7c086c02008-01-02 03:52:38 +00001930 """Read one line, using input() when appropriate."""
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001931 if self.input is sys.stdin:
Guido van Rossum7c086c02008-01-02 03:52:38 +00001932 return input(prompt)
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001933 else:
1934 self.output.write(prompt)
1935 self.output.flush()
1936 return self.input.readline()
1937
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001938 def help(self, request):
1939 if type(request) is type(''):
R. David Murray1f1b9d32009-05-27 20:56:59 +00001940 request = request.strip()
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001941 if request == 'keywords': self.listkeywords()
Georg Brandldb7b6b92009-01-01 15:53:14 +00001942 elif request == 'symbols': self.listsymbols()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001943 elif request == 'topics': self.listtopics()
1944 elif request == 'modules': self.listmodules()
1945 elif request[:8] == 'modules ':
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001946 self.listmodules(request.split()[1])
Georg Brandldb7b6b92009-01-01 15:53:14 +00001947 elif request in self.symbols: self.showsymbol(request)
Ezio Melottib185a042011-04-28 07:42:55 +03001948 elif request in ['True', 'False', 'None']:
1949 # special case these keywords since they are objects too
1950 doc(eval(request), 'Help on %s:')
Raymond Hettinger54f02222002-06-01 14:18:47 +00001951 elif request in self.keywords: self.showtopic(request)
1952 elif request in self.topics: self.showtopic(request)
Georg Brandld80d5f42010-12-03 07:47:22 +00001953 elif request: doc(request, 'Help on %s:', output=self._output)
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001954 else: doc(str, 'Help on %s:', output=self._output)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001955 elif isinstance(request, Helper): self()
Georg Brandld80d5f42010-12-03 07:47:22 +00001956 else: doc(request, 'Help on %s:', output=self._output)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001957 self.output.write('\n')
1958
1959 def intro(self):
1960 self.output.write('''
Serhiy Storchaka885bdc42016-02-11 13:10:36 +02001961Welcome to Python {0}'s help utility!
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001962
1963If this is your first time using Python, you should definitely check out
oldke5681b92017-12-28 22:37:46 +08001964the tutorial on the Internet at https://docs.python.org/{0}/tutorial/.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001965
1966Enter the name of any module, keyword, or topic to get help on writing
1967Python programs and using Python modules. To quit this help utility and
1968return to the interpreter, just type "quit".
1969
Terry Jan Reedy34200572013-02-11 02:23:13 -05001970To get a list of available modules, keywords, symbols, or topics, type
1971"modules", "keywords", "symbols", or "topics". Each module also comes
1972with a one-line summary of what it does; to list the modules whose name
1973or summary contain a given string such as "spam", type "modules spam".
Serhiy Storchaka885bdc42016-02-11 13:10:36 +02001974'''.format('%d.%d' % sys.version_info[:2]))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001975
1976 def list(self, items, columns=4, width=80):
Guido van Rossum486364b2007-06-30 05:01:58 +00001977 items = list(sorted(items))
1978 colw = width // columns
1979 rows = (len(items) + columns - 1) // columns
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001980 for row in range(rows):
1981 for col in range(columns):
1982 i = col * rows + row
1983 if i < len(items):
1984 self.output.write(items[i])
1985 if col < columns - 1:
Guido van Rossum486364b2007-06-30 05:01:58 +00001986 self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001987 self.output.write('\n')
1988
1989 def listkeywords(self):
1990 self.output.write('''
1991Here is a list of the Python keywords. Enter any keyword to get more help.
1992
1993''')
1994 self.list(self.keywords.keys())
1995
Georg Brandldb7b6b92009-01-01 15:53:14 +00001996 def listsymbols(self):
1997 self.output.write('''
1998Here is a list of the punctuation symbols which Python assigns special meaning
1999to. Enter any symbol to get more help.
2000
2001''')
2002 self.list(self.symbols.keys())
2003
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002004 def listtopics(self):
2005 self.output.write('''
2006Here is a list of available topics. Enter any topic name to get more help.
2007
2008''')
2009 self.list(self.topics.keys())
2010
Georg Brandldb7b6b92009-01-01 15:53:14 +00002011 def showtopic(self, topic, more_xrefs=''):
Georg Brandl6b38daa2008-06-01 21:05:17 +00002012 try:
Georg Brandl5617db82009-04-27 16:28:57 +00002013 import pydoc_data.topics
Brett Cannoncd171c82013-07-04 17:43:24 -04002014 except ImportError:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002015 self.output.write('''
Georg Brandl6b38daa2008-06-01 21:05:17 +00002016Sorry, topic and keyword documentation is not available because the
Georg Brandl5617db82009-04-27 16:28:57 +00002017module "pydoc_data.topics" could not be found.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002018''')
2019 return
2020 target = self.topics.get(topic, self.keywords.get(topic))
2021 if not target:
2022 self.output.write('no documentation found for %s\n' % repr(topic))
2023 return
2024 if type(target) is type(''):
Georg Brandldb7b6b92009-01-01 15:53:14 +00002025 return self.showtopic(target, more_xrefs)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002026
Georg Brandl6b38daa2008-06-01 21:05:17 +00002027 label, xrefs = target
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002028 try:
Georg Brandl5617db82009-04-27 16:28:57 +00002029 doc = pydoc_data.topics.topics[label]
Georg Brandl6b38daa2008-06-01 21:05:17 +00002030 except KeyError:
2031 self.output.write('no documentation found for %s\n' % repr(topic))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002032 return
Berker Peksagd04f46c2018-07-23 08:37:47 +03002033 doc = doc.strip() + '\n'
Georg Brandldb7b6b92009-01-01 15:53:14 +00002034 if more_xrefs:
2035 xrefs = (xrefs or '') + ' ' + more_xrefs
Ka-Ping Yeeda793892001-04-13 11:02:51 +00002036 if xrefs:
Brett Cannon1448ecf2013-10-04 11:38:59 -04002037 import textwrap
2038 text = 'Related help topics: ' + ', '.join(xrefs.split()) + '\n'
2039 wrapped_text = textwrap.wrap(text, 72)
Berker Peksagd04f46c2018-07-23 08:37:47 +03002040 doc += '\n%s\n' % '\n'.join(wrapped_text)
2041 pager(doc)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002042
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002043 def _gettopic(self, topic, more_xrefs=''):
2044 """Return unbuffered tuple of (topic, xrefs).
2045
Georg Brandld2f38572011-01-30 08:37:19 +00002046 If an error occurs here, the exception is caught and displayed by
2047 the url handler.
2048
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002049 This function duplicates the showtopic method but returns its
2050 result directly so it can be formatted for display in an html page.
2051 """
2052 try:
2053 import pydoc_data.topics
Brett Cannoncd171c82013-07-04 17:43:24 -04002054 except ImportError:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002055 return('''
2056Sorry, topic and keyword documentation is not available because the
2057module "pydoc_data.topics" could not be found.
2058''' , '')
2059 target = self.topics.get(topic, self.keywords.get(topic))
2060 if not target:
Georg Brandld2f38572011-01-30 08:37:19 +00002061 raise ValueError('could not find topic')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002062 if isinstance(target, str):
2063 return self._gettopic(target, more_xrefs)
2064 label, xrefs = target
Georg Brandld2f38572011-01-30 08:37:19 +00002065 doc = pydoc_data.topics.topics[label]
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002066 if more_xrefs:
2067 xrefs = (xrefs or '') + ' ' + more_xrefs
2068 return doc, xrefs
2069
Georg Brandldb7b6b92009-01-01 15:53:14 +00002070 def showsymbol(self, symbol):
2071 target = self.symbols[symbol]
2072 topic, _, xrefs = target.partition(' ')
2073 self.showtopic(topic, xrefs)
2074
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002075 def listmodules(self, key=''):
2076 if key:
2077 self.output.write('''
Terry Jan Reedy34200572013-02-11 02:23:13 -05002078Here is a list of modules whose name or summary contains '{}'.
2079If there are any, enter a module name to get more help.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002080
Terry Jan Reedy34200572013-02-11 02:23:13 -05002081'''.format(key))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002082 apropos(key)
2083 else:
2084 self.output.write('''
2085Please wait a moment while I gather a list of all available modules...
2086
2087''')
2088 modules = {}
2089 def callback(path, modname, desc, modules=modules):
2090 if modname and modname[-9:] == '.__init__':
2091 modname = modname[:-9] + ' (package)'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002092 if modname.find('.') < 0:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002093 modules[modname] = 1
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002094 def onerror(modname):
2095 callback(None, modname, None)
2096 ModuleScanner().run(callback, onerror=onerror)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002097 self.list(modules.keys())
2098 self.output.write('''
2099Enter any module name to get more help. Or, type "modules spam" to search
Terry Jan Reedy34200572013-02-11 02:23:13 -05002100for modules whose name or summary contain the string "spam".
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002101''')
2102
Georg Brandl78aa3962010-07-31 21:51:48 +00002103help = Helper()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002104
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002105class ModuleScanner:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002106 """An interruptible scanner that searches module synopses."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002107
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002108 def run(self, callback, key=None, completer=None, onerror=None):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002109 if key: key = key.lower()
Guido van Rossum8ca162f2002-04-07 06:36:23 +00002110 self.quit = False
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002111 seen = {}
2112
2113 for modname in sys.builtin_module_names:
Ka-Ping Yee239432a2001-03-02 02:45:08 +00002114 if modname != '__main__':
2115 seen[modname] = 1
Ka-Ping Yee66246962001-04-12 11:59:50 +00002116 if key is None:
2117 callback(None, modname, '')
2118 else:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002119 name = __import__(modname).__doc__ or ''
2120 desc = name.split('\n')[0]
2121 name = modname + ' - ' + desc
2122 if name.lower().find(key) >= 0:
Ka-Ping Yee66246962001-04-12 11:59:50 +00002123 callback(None, modname, desc)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002124
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002125 for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002126 if self.quit:
2127 break
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002128
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002129 if key is None:
2130 callback(None, modname, '')
2131 else:
Georg Brandl126c8792009-04-05 15:05:48 +00002132 try:
Eric Snow3a62d142014-01-06 20:42:59 -07002133 spec = pkgutil._get_spec(importer, modname)
Georg Brandl126c8792009-04-05 15:05:48 +00002134 except SyntaxError:
2135 # raised by tests for bad coding cookies or BOM
2136 continue
Eric Snow3a62d142014-01-06 20:42:59 -07002137 loader = spec.loader
Georg Brandl126c8792009-04-05 15:05:48 +00002138 if hasattr(loader, 'get_source'):
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002139 try:
2140 source = loader.get_source(modname)
Nick Coghlan2824cb52012-07-15 22:12:14 +10002141 except Exception:
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002142 if onerror:
2143 onerror(modname)
2144 continue
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002145 desc = source_synopsis(io.StringIO(source)) or ''
Georg Brandl126c8792009-04-05 15:05:48 +00002146 if hasattr(loader, 'get_filename'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002147 path = loader.get_filename(modname)
Ka-Ping Yee66246962001-04-12 11:59:50 +00002148 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002149 path = None
2150 else:
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002151 try:
Brett Cannon2a17bde2014-05-30 14:55:29 -04002152 module = importlib._bootstrap._load(spec)
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002153 except ImportError:
2154 if onerror:
2155 onerror(modname)
2156 continue
Benjamin Peterson54237f92015-02-16 19:45:01 -05002157 desc = module.__doc__.splitlines()[0] if module.__doc__ else ''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002158 path = getattr(module,'__file__',None)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002159 name = modname + ' - ' + desc
2160 if name.lower().find(key) >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002161 callback(path, modname, desc)
2162
2163 if completer:
2164 completer()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002165
2166def apropos(key):
2167 """Print all the one-line module summaries that contain a substring."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002168 def callback(path, modname, desc):
2169 if modname[-9:] == '.__init__':
2170 modname = modname[:-9] + ' (package)'
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002171 print(modname, desc and '- ' + desc)
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002172 def onerror(modname):
2173 pass
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002174 with warnings.catch_warnings():
2175 warnings.filterwarnings('ignore') # ignore problems during import
2176 ModuleScanner().run(callback, key, onerror=onerror)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002177
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002178# --------------------------------------- enhanced Web browser interface
2179
Feanil Patel6a396c92017-09-14 17:54:09 -04002180def _start_server(urlhandler, hostname, port):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002181 """Start an HTTP server thread on a specific port.
2182
2183 Start an HTML/text server thread, so HTML or text documents can be
2184 browsed dynamically and interactively with a Web browser. Example use:
2185
2186 >>> import time
2187 >>> import pydoc
2188
2189 Define a URL handler. To determine what the client is asking
2190 for, check the URL and content_type.
2191
2192 Then get or generate some text or HTML code and return it.
2193
2194 >>> def my_url_handler(url, content_type):
2195 ... text = 'the URL sent was: (%s, %s)' % (url, content_type)
2196 ... return text
2197
2198 Start server thread on port 0.
2199 If you use port 0, the server will pick a random port number.
2200 You can then use serverthread.port to get the port number.
2201
2202 >>> port = 0
2203 >>> serverthread = pydoc._start_server(my_url_handler, port)
2204
2205 Check that the server is really started. If it is, open browser
2206 and get first page. Use serverthread.url as the starting page.
2207
2208 >>> if serverthread.serving:
2209 ... import webbrowser
2210
2211 The next two lines are commented out so a browser doesn't open if
2212 doctest is run on this module.
2213
2214 #... webbrowser.open(serverthread.url)
2215 #True
2216
2217 Let the server do its thing. We just need to monitor its status.
2218 Use time.sleep so the loop doesn't hog the CPU.
2219
Victor Stinner2cf4c202018-12-17 09:36:36 +01002220 >>> starttime = time.monotonic()
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002221 >>> timeout = 1 #seconds
2222
2223 This is a short timeout for testing purposes.
2224
2225 >>> while serverthread.serving:
2226 ... time.sleep(.01)
Victor Stinner2cf4c202018-12-17 09:36:36 +01002227 ... if serverthread.serving and time.monotonic() - starttime > timeout:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002228 ... serverthread.stop()
2229 ... break
2230
2231 Print any errors that may have occurred.
2232
2233 >>> print(serverthread.error)
2234 None
2235 """
2236 import http.server
2237 import email.message
2238 import select
2239 import threading
2240
2241 class DocHandler(http.server.BaseHTTPRequestHandler):
2242
2243 def do_GET(self):
2244 """Process a request from an HTML browser.
2245
2246 The URL received is in self.path.
2247 Get an HTML page from self.urlhandler and send it.
2248 """
2249 if self.path.endswith('.css'):
2250 content_type = 'text/css'
2251 else:
2252 content_type = 'text/html'
2253 self.send_response(200)
Georg Brandld2f38572011-01-30 08:37:19 +00002254 self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002255 self.end_headers()
2256 self.wfile.write(self.urlhandler(
2257 self.path, content_type).encode('utf-8'))
2258
2259 def log_message(self, *args):
2260 # Don't log messages.
2261 pass
2262
2263 class DocServer(http.server.HTTPServer):
2264
Feanil Patel6a396c92017-09-14 17:54:09 -04002265 def __init__(self, host, port, callback):
2266 self.host = host
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +08002267 self.address = (self.host, port)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002268 self.callback = callback
2269 self.base.__init__(self, self.address, self.handler)
2270 self.quit = False
2271
2272 def serve_until_quit(self):
2273 while not self.quit:
2274 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
2275 if rd:
2276 self.handle_request()
Victor Stinnera3abd1d2011-01-03 16:12:39 +00002277 self.server_close()
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002278
2279 def server_activate(self):
2280 self.base.server_activate(self)
2281 if self.callback:
2282 self.callback(self)
2283
2284 class ServerThread(threading.Thread):
2285
Feanil Patel6a396c92017-09-14 17:54:09 -04002286 def __init__(self, urlhandler, host, port):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002287 self.urlhandler = urlhandler
Feanil Patel6a396c92017-09-14 17:54:09 -04002288 self.host = host
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002289 self.port = int(port)
2290 threading.Thread.__init__(self)
2291 self.serving = False
2292 self.error = None
2293
2294 def run(self):
2295 """Start the server."""
2296 try:
2297 DocServer.base = http.server.HTTPServer
2298 DocServer.handler = DocHandler
2299 DocHandler.MessageClass = email.message.Message
2300 DocHandler.urlhandler = staticmethod(self.urlhandler)
Feanil Patel6a396c92017-09-14 17:54:09 -04002301 docsvr = DocServer(self.host, self.port, self.ready)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002302 self.docserver = docsvr
2303 docsvr.serve_until_quit()
2304 except Exception as e:
2305 self.error = e
2306
2307 def ready(self, server):
2308 self.serving = True
2309 self.host = server.host
2310 self.port = server.server_port
2311 self.url = 'http://%s:%d/' % (self.host, self.port)
2312
2313 def stop(self):
2314 """Stop the server and this thread nicely"""
2315 self.docserver.quit = True
Victor Stinner4cab2cd2017-08-21 23:24:40 +02002316 self.join()
2317 # explicitly break a reference cycle: DocServer.callback
2318 # has indirectly a reference to ServerThread.
2319 self.docserver = None
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002320 self.serving = False
2321 self.url = None
2322
Feanil Patel6a396c92017-09-14 17:54:09 -04002323 thread = ServerThread(urlhandler, hostname, port)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002324 thread.start()
2325 # Wait until thread.serving is True to make sure we are
2326 # really up before returning.
2327 while not thread.error and not thread.serving:
2328 time.sleep(.01)
2329 return thread
2330
2331
2332def _url_handler(url, content_type="text/html"):
2333 """The pydoc url handler for use with the pydoc server.
2334
2335 If the content_type is 'text/css', the _pydoc.css style
2336 sheet is read and returned if it exits.
2337
2338 If the content_type is 'text/html', then the result of
2339 get_html_page(url) is returned.
2340 """
2341 class _HTMLDoc(HTMLDoc):
2342
2343 def page(self, title, contents):
2344 """Format an HTML page."""
2345 css_path = "pydoc_data/_pydoc.css"
2346 css_link = (
2347 '<link rel="stylesheet" type="text/css" href="%s">' %
2348 css_path)
2349 return '''\
2350<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Georg Brandld2f38572011-01-30 08:37:19 +00002351<html><head><title>Pydoc: %s</title>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002352<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Georg Brandld2f38572011-01-30 08:37:19 +00002353%s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div>
2354</body></html>''' % (title, css_link, html_navbar(), contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002355
2356 def filelink(self, url, path):
2357 return '<a href="getfile?key=%s">%s</a>' % (url, path)
2358
2359
2360 html = _HTMLDoc()
2361
2362 def html_navbar():
Georg Brandld2f38572011-01-30 08:37:19 +00002363 version = html.escape("%s [%s, %s]" % (platform.python_version(),
2364 platform.python_build()[0],
2365 platform.python_compiler()))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002366 return """
2367 <div style='float:left'>
Georg Brandld2f38572011-01-30 08:37:19 +00002368 Python %s<br>%s
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002369 </div>
2370 <div style='float:right'>
2371 <div style='text-align:center'>
2372 <a href="index.html">Module Index</a>
2373 : <a href="topics.html">Topics</a>
2374 : <a href="keywords.html">Keywords</a>
2375 </div>
2376 <div>
Georg Brandld2f38572011-01-30 08:37:19 +00002377 <form action="get" style='display:inline;'>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002378 <input type=text name=key size=15>
2379 <input type=submit value="Get">
Georg Brandld2f38572011-01-30 08:37:19 +00002380 </form>&nbsp;
2381 <form action="search" style='display:inline;'>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002382 <input type=text name=key size=15>
2383 <input type=submit value="Search">
2384 </form>
2385 </div>
2386 </div>
Georg Brandld2f38572011-01-30 08:37:19 +00002387 """ % (version, html.escape(platform.platform(terse=True)))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002388
2389 def html_index():
2390 """Module Index page."""
2391
2392 def bltinlink(name):
2393 return '<a href="%s.html">%s</a>' % (name, name)
2394
2395 heading = html.heading(
2396 '<big><big><strong>Index of Modules</strong></big></big>',
2397 '#ffffff', '#7799ee')
2398 names = [name for name in sys.builtin_module_names
2399 if name != '__main__']
2400 contents = html.multicolumn(names, bltinlink)
2401 contents = [heading, '<p>' + html.bigsection(
2402 'Built-in Modules', '#ffffff', '#ee77aa', contents)]
2403
2404 seen = {}
2405 for dir in sys.path:
2406 contents.append(html.index(dir, seen))
2407
2408 contents.append(
2409 '<p align=right><font color="#909090" face="helvetica,'
2410 'arial"><strong>pydoc</strong> by Ka-Ping Yee'
2411 '&lt;ping@lfw.org&gt;</font>')
Nick Coghlanecace282010-12-03 16:08:46 +00002412 return 'Index of Modules', ''.join(contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002413
2414 def html_search(key):
2415 """Search results page."""
2416 # scan for modules
2417 search_result = []
2418
2419 def callback(path, modname, desc):
2420 if modname[-9:] == '.__init__':
2421 modname = modname[:-9] + ' (package)'
2422 search_result.append((modname, desc and '- ' + desc))
2423
2424 with warnings.catch_warnings():
2425 warnings.filterwarnings('ignore') # ignore problems during import
Martin Panter9ad0aae2015-11-06 00:27:14 +00002426 def onerror(modname):
2427 pass
2428 ModuleScanner().run(callback, key, onerror=onerror)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002429
2430 # format page
2431 def bltinlink(name):
2432 return '<a href="%s.html">%s</a>' % (name, name)
2433
2434 results = []
2435 heading = html.heading(
2436 '<big><big><strong>Search Results</strong></big></big>',
2437 '#ffffff', '#7799ee')
2438 for name, desc in search_result:
2439 results.append(bltinlink(name) + desc)
2440 contents = heading + html.bigsection(
2441 'key = %s' % key, '#ffffff', '#ee77aa', '<br>'.join(results))
Nick Coghlanecace282010-12-03 16:08:46 +00002442 return 'Search Results', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002443
2444 def html_getfile(path):
2445 """Get and display a source file listing safely."""
Zachary Wareeb432142014-07-10 11:18:00 -05002446 path = urllib.parse.unquote(path)
Victor Stinner91e08772011-07-05 14:30:41 +02002447 with tokenize.open(path) as fp:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002448 lines = html.escape(fp.read())
2449 body = '<pre>%s</pre>' % lines
2450 heading = html.heading(
2451 '<big><big><strong>File Listing</strong></big></big>',
2452 '#ffffff', '#7799ee')
2453 contents = heading + html.bigsection(
2454 'File: %s' % path, '#ffffff', '#ee77aa', body)
Nick Coghlanecace282010-12-03 16:08:46 +00002455 return 'getfile %s' % path, contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002456
2457 def html_topics():
2458 """Index of topic texts available."""
2459
2460 def bltinlink(name):
Georg Brandld2f38572011-01-30 08:37:19 +00002461 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002462
2463 heading = html.heading(
2464 '<big><big><strong>INDEX</strong></big></big>',
2465 '#ffffff', '#7799ee')
2466 names = sorted(Helper.topics.keys())
2467
2468 contents = html.multicolumn(names, bltinlink)
2469 contents = heading + html.bigsection(
2470 'Topics', '#ffffff', '#ee77aa', contents)
Nick Coghlanecace282010-12-03 16:08:46 +00002471 return 'Topics', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002472
2473 def html_keywords():
2474 """Index of keywords."""
2475 heading = html.heading(
2476 '<big><big><strong>INDEX</strong></big></big>',
2477 '#ffffff', '#7799ee')
2478 names = sorted(Helper.keywords.keys())
2479
2480 def bltinlink(name):
Georg Brandld2f38572011-01-30 08:37:19 +00002481 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002482
2483 contents = html.multicolumn(names, bltinlink)
2484 contents = heading + html.bigsection(
2485 'Keywords', '#ffffff', '#ee77aa', contents)
Nick Coghlanecace282010-12-03 16:08:46 +00002486 return 'Keywords', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002487
2488 def html_topicpage(topic):
2489 """Topic or keyword help page."""
2490 buf = io.StringIO()
2491 htmlhelp = Helper(buf, buf)
2492 contents, xrefs = htmlhelp._gettopic(topic)
2493 if topic in htmlhelp.keywords:
2494 title = 'KEYWORD'
2495 else:
2496 title = 'TOPIC'
2497 heading = html.heading(
2498 '<big><big><strong>%s</strong></big></big>' % title,
2499 '#ffffff', '#7799ee')
Georg Brandld2f38572011-01-30 08:37:19 +00002500 contents = '<pre>%s</pre>' % html.markup(contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002501 contents = html.bigsection(topic , '#ffffff','#ee77aa', contents)
Georg Brandld2f38572011-01-30 08:37:19 +00002502 if xrefs:
2503 xrefs = sorted(xrefs.split())
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002504
Georg Brandld2f38572011-01-30 08:37:19 +00002505 def bltinlink(name):
2506 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002507
Georg Brandld2f38572011-01-30 08:37:19 +00002508 xrefs = html.multicolumn(xrefs, bltinlink)
2509 xrefs = html.section('Related help topics: ',
2510 '#ffffff', '#ee77aa', xrefs)
Nick Coghlanecace282010-12-03 16:08:46 +00002511 return ('%s %s' % (title, topic),
2512 ''.join((heading, contents, xrefs)))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002513
Georg Brandld2f38572011-01-30 08:37:19 +00002514 def html_getobj(url):
2515 obj = locate(url, forceload=1)
2516 if obj is None and url != 'None':
2517 raise ValueError('could not find object')
2518 title = describe(obj)
2519 content = html.document(obj, url)
2520 return title, content
2521
2522 def html_error(url, exc):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002523 heading = html.heading(
2524 '<big><big><strong>Error</strong></big></big>',
Georg Brandld2f38572011-01-30 08:37:19 +00002525 '#ffffff', '#7799ee')
2526 contents = '<br>'.join(html.escape(line) for line in
2527 format_exception_only(type(exc), exc))
2528 contents = heading + html.bigsection(url, '#ffffff', '#bb0000',
2529 contents)
2530 return "Error - %s" % url, contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002531
2532 def get_html_page(url):
2533 """Generate an HTML page for url."""
Georg Brandld2f38572011-01-30 08:37:19 +00002534 complete_url = url
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002535 if url.endswith('.html'):
2536 url = url[:-5]
Georg Brandld2f38572011-01-30 08:37:19 +00002537 try:
2538 if url in ("", "index"):
2539 title, content = html_index()
2540 elif url == "topics":
2541 title, content = html_topics()
2542 elif url == "keywords":
2543 title, content = html_keywords()
2544 elif '=' in url:
2545 op, _, url = url.partition('=')
2546 if op == "search?key":
2547 title, content = html_search(url)
2548 elif op == "getfile?key":
2549 title, content = html_getfile(url)
2550 elif op == "topic?key":
2551 # try topics first, then objects.
2552 try:
2553 title, content = html_topicpage(url)
2554 except ValueError:
2555 title, content = html_getobj(url)
2556 elif op == "get?key":
2557 # try objects first, then topics.
2558 if url in ("", "index"):
2559 title, content = html_index()
2560 else:
2561 try:
2562 title, content = html_getobj(url)
2563 except ValueError:
2564 title, content = html_topicpage(url)
2565 else:
2566 raise ValueError('bad pydoc url')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002567 else:
Georg Brandld2f38572011-01-30 08:37:19 +00002568 title, content = html_getobj(url)
2569 except Exception as exc:
2570 # Catch any errors and display them in an error page.
2571 title, content = html_error(complete_url, exc)
2572 return html.page(title, content)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002573
2574 if url.startswith('/'):
2575 url = url[1:]
2576 if content_type == 'text/css':
2577 path_here = os.path.dirname(os.path.realpath(__file__))
Georg Brandld2f38572011-01-30 08:37:19 +00002578 css_path = os.path.join(path_here, url)
2579 with open(css_path) as fp:
2580 return ''.join(fp.readlines())
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002581 elif content_type == 'text/html':
2582 return get_html_page(url)
Georg Brandld2f38572011-01-30 08:37:19 +00002583 # Errors outside the url handler are caught by the server.
2584 raise TypeError('unknown content type %r for url %s' % (content_type, url))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002585
2586
Feanil Patel6a396c92017-09-14 17:54:09 -04002587def browse(port=0, *, open_browser=True, hostname='localhost'):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002588 """Start the enhanced pydoc Web server and open a Web browser.
2589
2590 Use port '0' to start the server on an arbitrary port.
2591 Set open_browser to False to suppress opening a browser.
2592 """
2593 import webbrowser
Feanil Patel6a396c92017-09-14 17:54:09 -04002594 serverthread = _start_server(_url_handler, hostname, port)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002595 if serverthread.error:
2596 print(serverthread.error)
2597 return
2598 if serverthread.serving:
2599 server_help_msg = 'Server commands: [b]rowser, [q]uit'
2600 if open_browser:
2601 webbrowser.open(serverthread.url)
2602 try:
2603 print('Server ready at', serverthread.url)
2604 print(server_help_msg)
2605 while serverthread.serving:
2606 cmd = input('server> ')
2607 cmd = cmd.lower()
2608 if cmd == 'q':
2609 break
2610 elif cmd == 'b':
2611 webbrowser.open(serverthread.url)
2612 else:
2613 print(server_help_msg)
2614 except (KeyboardInterrupt, EOFError):
2615 print()
2616 finally:
2617 if serverthread.serving:
2618 serverthread.stop()
2619 print('Server stopped')
2620
2621
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002622# -------------------------------------------------- command-line interface
2623
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002624def ispath(x):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002625 return isinstance(x, str) and x.find(os.sep) >= 0
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002626
Nick Coghlan82a94812018-04-15 21:52:57 +10002627def _get_revised_path(given_path, argv0):
2628 """Ensures current directory is on returned path, and argv0 directory is not
2629
2630 Exception: argv0 dir is left alone if it's also pydoc's directory.
2631
2632 Returns a new path entry list, or None if no adjustment is needed.
2633 """
2634 # Scripts may get the current directory in their path by default if they're
2635 # run with the -m switch, or directly from the current directory.
2636 # The interactive prompt also allows imports from the current directory.
2637
2638 # Accordingly, if the current directory is already present, don't make
2639 # any changes to the given_path
2640 if '' in given_path or os.curdir in given_path or os.getcwd() in given_path:
2641 return None
2642
2643 # Otherwise, add the current directory to the given path, and remove the
2644 # script directory (as long as the latter isn't also pydoc's directory.
2645 stdlib_dir = os.path.dirname(__file__)
2646 script_dir = os.path.dirname(argv0)
2647 revised_path = given_path.copy()
2648 if script_dir in given_path and not os.path.samefile(script_dir, stdlib_dir):
2649 revised_path.remove(script_dir)
2650 revised_path.insert(0, os.getcwd())
2651 return revised_path
2652
2653
2654# Note: the tests only cover _get_revised_path, not _adjust_cli_path itself
2655def _adjust_cli_sys_path():
Nick Coghlan1a5c4bd2018-04-15 23:32:05 +10002656 """Ensures current directory is on sys.path, and __main__ directory is not.
Nick Coghlan82a94812018-04-15 21:52:57 +10002657
2658 Exception: __main__ dir is left alone if it's also pydoc's directory.
2659 """
2660 revised_path = _get_revised_path(sys.path, sys.argv[0])
2661 if revised_path is not None:
2662 sys.path[:] = revised_path
2663
2664
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002665def cli():
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002666 """Command-line interface (looks at sys.argv to decide what to do)."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002667 import getopt
Guido van Rossum756aa932007-04-07 03:04:01 +00002668 class BadUsage(Exception): pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002669
Nick Coghlan82a94812018-04-15 21:52:57 +10002670 _adjust_cli_sys_path()
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002671
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00002672 try:
Feanil Patel6a396c92017-09-14 17:54:09 -04002673 opts, args = getopt.getopt(sys.argv[1:], 'bk:n:p:w')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002674 writing = False
2675 start_server = False
2676 open_browser = False
Feanil Patel6a396c92017-09-14 17:54:09 -04002677 port = 0
2678 hostname = 'localhost'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002679 for opt, val in opts:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002680 if opt == '-b':
2681 start_server = True
2682 open_browser = True
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002683 if opt == '-k':
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002684 apropos(val)
2685 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002686 if opt == '-p':
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002687 start_server = True
2688 port = val
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002689 if opt == '-w':
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002690 writing = True
Feanil Patel6a396c92017-09-14 17:54:09 -04002691 if opt == '-n':
2692 start_server = True
2693 hostname = val
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002694
Benjamin Petersonb29614e2012-10-09 11:16:03 -04002695 if start_server:
Feanil Patel6a396c92017-09-14 17:54:09 -04002696 browse(port, hostname=hostname, open_browser=open_browser)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002697 return
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002698
2699 if not args: raise BadUsage
2700 for arg in args:
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00002701 if ispath(arg) and not os.path.exists(arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002702 print('file %r does not exist' % arg)
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00002703 break
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002704 try:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002705 if ispath(arg) and os.path.isfile(arg):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002706 arg = importfile(arg)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002707 if writing:
2708 if ispath(arg) and os.path.isdir(arg):
2709 writedocs(arg)
2710 else:
2711 writedoc(arg)
2712 else:
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002713 help.help(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +00002714 except ErrorDuringImport as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002715 print(value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002716
2717 except (getopt.error, BadUsage):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002718 cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002719 print("""pydoc - the Python documentation tool
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002720
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002721{cmd} <name> ...
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002722 Show text documentation on something. <name> may be the name of a
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002723 Python keyword, topic, function, module, or package, or a dotted
2724 reference to a class or function within a module or module in a
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002725 package. If <name> contains a '{sep}', it is used as the path to a
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002726 Python source file to document. If name is 'keywords', 'topics',
2727 or 'modules', a listing of these things is displayed.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002728
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002729{cmd} -k <keyword>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002730 Search for a keyword in the synopsis lines of all available modules.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002731
Feanil Patel6a396c92017-09-14 17:54:09 -04002732{cmd} -n <hostname>
2733 Start an HTTP server with the given hostname (default: localhost).
2734
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002735{cmd} -p <port>
2736 Start an HTTP server on the given port on the local machine. Port
2737 number 0 can be used to get an arbitrary unused port.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002738
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002739{cmd} -b
2740 Start an HTTP server on an arbitrary unused port and open a Web browser
Feanil Patel6a396c92017-09-14 17:54:09 -04002741 to interactively browse documentation. This option can be used in
2742 combination with -n and/or -p.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002743
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002744{cmd} -w <name> ...
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002745 Write out the HTML documentation for a module to a file in the current
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002746 directory. If <name> contains a '{sep}', it is treated as a filename; if
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00002747 it names a directory, documentation is written for all the contents.
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002748""".format(cmd=cmd, sep=os.sep))
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002749
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002750if __name__ == '__main__':
2751 cli()