Debian Codegraph @

lib-python/3/pydoc.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 """Generate Python documentation in HTML or text for interactive use.
3
4 At the Python interactive prompt, calling help(thing) on a Python object
5 documents the object, and calling help() starts up an interactive
6 help session.
7
8 Or, at the shell command line outside of Python:
9
10 Run "pydoc <name>" to show documentation on something. <name> may be
11 the name of a function, module, package, or a dotted reference to a
12 class or function within a module or module in a package. If the
13 argument contains a path segment delimiter (e.g. slash on Unix,
14 backslash on Windows) it is treated as the path to a Python source file.
15
16 Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
17 of all available modules.
18
19 Run "pydoc -n <hostname>" to start an HTTP server with the given
20 hostname (default: localhost) on the local machine.
21
22 Run "pydoc -p <port>" to start an HTTP server on the given port on the
23 local machine. Port number 0 can be used to get an arbitrary unused port.
24
25 Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
26 open a web browser to interactively browse documentation. Combine with
27 the -n and -p options to control the hostname and port used.
28
29 Run "pydoc -w <name>" to write out the HTML documentation for a module
30 to a file named "<name>.html".
31
32 Module docs for core modules are assumed to be in
33
34 https://docs.python.org/X.Y/library/
35
36 This can be overridden by setting the PYTHONDOCS environment variable
37 to a different URL or to a local directory containing the Library
38 Reference Manual pages.
39 """
40 __all__ = ['help']
41 __author__ = "Ka-Ping Yee <[email protected]>"
42 __date__ = "26 February 2001"
43
44 __credits__ = """Guido van Rossum, for an excellent programming language.
45 Tommy Burnette, the original creator of manpy.
46 Paul Prescod, for all his work on onlinehelp.
47 Richard Chamberlain, for the first implementation of textdoc.
48 """
49
50 # Known bugs that can't be fixed here:
51 # - synopsis() cannot be prevented from clobbering existing
52 # loaded modules.
53 # - 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.
56
57 import __future__
58 import builtins
59 import importlib._bootstrap
60 import importlib._bootstrap_external
61 import importlib.machinery
62 import importlib.util
63 import inspect
64 import io
65 import os
66 import pkgutil
67 import platform
68 import re
69 import sys
70 import sysconfig
71 import time
72 import tokenize
73 import urllib.parse
74 import warnings
75 from collections import deque
76 from reprlib import Repr
77 from traceback import format_exception_only
78
79
80 # --------------------------------------------------------- common routines
81
82 def pathdirs():
83 """Convert sys.path into a list of absolute, existing, unique paths."""
84 dirs = []
85 normdirs = []
86 for dir in sys.path:
87 dir = os.path.abspath(dir or '.')
88 normdir = os.path.normcase(dir)
89 if normdir not in normdirs and os.path.isdir(dir):
90 dirs.append(dir)
91 normdirs.append(normdir)
92 return dirs
93
94 def _findclass(func):
95 cls = sys.modules.get(func.__module__)
96 if cls is None:
97 return None
98 for name in func.__qualname__.split('.')[:-1]:
99 cls = getattr(cls, name)
100 if not inspect.isclass(cls):
101 return None
102 return cls
103
104 def _finddoc(obj):
105 if inspect.ismethod(obj):
106 name = obj.__func__.__name__
107 self = obj.__self__
108 if (inspect.isclass(self) and
109 getattr(getattr(self, name, None), '__func__') is obj.__func__):
110 # classmethod
111 cls = self
112 else:
113 cls = self.__class__
114 elif inspect.isfunction(obj):
115 name = obj.__name__
116 cls = _findclass(obj)
117 if cls is None or getattr(cls, name) is not obj:
118 return None
119 elif inspect.isbuiltin(obj):
120 name = obj.__name__
121 self = obj.__self__
122 if (inspect.isclass(self) and
123 self.__qualname__ + '.' + name == obj.__qualname__):
124 # classmethod
125 cls = self
126 else:
127 cls = self.__class__
128 # Should be tested before isdatadescriptor().
129 elif isinstance(obj, property):
130 func = obj.fget
131 name = func.__name__
132 cls = _findclass(func)
133 if cls is None or getattr(cls, name) is not obj:
134 return None
135 elif inspect.ismethoddescriptor(obj) or inspect.isdatadescriptor(obj):
136 name = obj.__name__
137 cls = obj.__objclass__
138 if getattr(cls, name) is not obj:
139 return None
140 if inspect.ismemberdescriptor(obj):
141 slots = getattr(cls, '__slots__', None)
142 if isinstance(slots, dict) and name in slots:
143 return slots[name]
144 else:
145 return None
146 for base in cls.__mro__:
147 try:
148 doc = _getowndoc(getattr(base, name))
149 except AttributeError:
150 continue
151 if doc is not None:
152 return doc
153 return None
154
155 def _getowndoc(obj):
156 """Get the documentation string for an object if it is not
157 inherited from its class."""
158 try:
159 doc = object.__getattribute__(obj, '__doc__')
160 if doc is None:
161 return None
162 if obj is not type:
163 typedoc = type(obj).__doc__
164 if isinstance(typedoc, str) and typedoc == doc:
165 return None
166 return doc
167 except AttributeError:
168 return None
169
170 def _getdoc(object):
171 """Get the documentation string for an object.
172
173 All tabs are expanded to spaces. To clean up docstrings that are
174 indented to line up with blocks of code, any whitespace than can be
175 uniformly removed from the second line onwards is removed."""
176 doc = _getowndoc(object)
177 if doc is None:
178 try:
179 doc = _finddoc(object)
180 except (AttributeError, TypeError):
181 return None
182 if not isinstance(doc, str):
183 return None
184 return inspect.cleandoc(doc)
185
186 def getdoc(object):
187 """Get the doc string or comments for an object."""
188 result = _getdoc(object) or inspect.getcomments(object)
189 return result and re.sub('^ *\n', '', result.rstrip()) or ''
190
191 def splitdoc(doc):
192 """Split a doc string into a synopsis line (if any) and the rest."""
193 lines = doc.strip().split('\n')
194 if len(lines) == 1:
195 return lines[0], ''
196 elif len(lines) >= 2 and not lines[1].rstrip():
197 return lines[0], '\n'.join(lines[2:])
198 return '', '\n'.join(lines)
199
200 def classname(object, modname):
201 """Get a class name and qualify it with a module name if necessary."""
202 name = object.__name__
203 if object.__module__ != modname:
204 name = object.__module__ + '.' + name
205 return name
206
207 def parentname(object, modname):
208 """Get a name of the enclosing class (qualified it with a module name
209 if necessary) or module."""
210 if '.' in object.__qualname__:
211 name = object.__qualname__.rpartition('.')[0]
212 if object.__module__ and object.__module__ != modname:
213 return object.__module__ + '.' + name
214 else:
215 return name
216 else:
217 if object.__module__ != modname:
218 return object.__module__
219
220 def isdata(object):
221 """Check if an object is of a type that probably means it's data."""
222 return not (inspect.ismodule(object) or inspect.isclass(object) or
223 inspect.isroutine(object) or inspect.isframe(object) or
224 inspect.istraceback(object) or inspect.iscode(object))
225
226 def replace(text, *pairs):
227 """Do a series of global replacements on a string."""
228 while pairs:
229 text = pairs[1].join(text.split(pairs[0]))
230 pairs = pairs[2:]
231 return text
232
233 def cram(text, maxlen):
234 """Omit part of a string if needed to make it fit in a maximum length."""
235 if len(text) > maxlen:
236 pre = max(0, (maxlen-3)//2)
237 post = max(0, maxlen-3-pre)
238 return text[:pre] + '...' + text[len(text)-post:]
239 return text
240
241 _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
242 def stripid(text):
243 """Remove the hexadecimal id from a Python object representation."""
244 # The behaviour of %p is implementation-dependent in terms of case.
245 return _re_stripid.sub(r'\1', text)
246
247 def _is_bound_method(fn):
248 """
249 Returns True if fn is a bound method, regardless of whether
250 fn was implemented in Python or in C.
251 """
252 if inspect.ismethod(fn):
253 return True
254 if inspect.isbuiltin(fn):
255 self = getattr(fn, '__self__', None)
256 return not (inspect.ismodule(self) or (self is None))
257 return False
258
259
260 def allmethods(cl):
261 methods = {}
262 for key, value in inspect.getmembers(cl, inspect.isroutine):
263 methods[key] = 1
264 for base in cl.__bases__:
265 methods.update(allmethods(base)) # all your base are belong to us
266 for key in methods.keys():
267 methods[key] = getattr(cl, key)
268 return methods
269
270 def _split_list(s, predicate):
271 """Split sequence s via predicate, and return pair ([true], [false]).
272
273 The return value is a 2-tuple of lists,
274 ([x for x in s if predicate(x)],
275 [x for x in s if not predicate(x)])
276 """
277
278 yes = []
279 no = []
280 for x in s:
281 if predicate(x):
282 yes.append(x)
283 else:
284 no.append(x)
285 return yes, no
286
287 _future_feature_names = set(__future__.all_feature_names)
288
289 def visiblename(name, all=None, obj=None):
290 """Decide whether to show documentation on a variable."""
291 # Certain special names are redundant or internal.
292 # XXX Remove __initializing__?
293 if name in {'__author__', '__builtins__', '__cached__', '__credits__',
294 '__date__', '__doc__', '__file__', '__spec__',
295 '__loader__', '__module__', '__name__', '__package__',
296 '__path__', '__qualname__', '__slots__', '__version__'}:
297 return 0
298 # Private names are hidden, but special names are displayed.
299 if name.startswith('__') and name.endswith('__'): return 1
300 # Namedtuples have public fields and methods with a single leading underscore
301 if name.startswith('_') and hasattr(obj, '_fields'):
302 return True
303 # Ignore __future__ imports.
304 if obj is not __future__ and name in _future_feature_names:
305 if isinstance(getattr(obj, name, None), __future__._Feature):
306 return False
307 if all is not None:
308 # only document that which the programmer exported in __all__
309 return name in all
310 else:
311 return not name.startswith('_')
312
313 def classify_class_attrs(object):
314 """Wrap inspect.classify_class_attrs, with fixup for data descriptors and bound methods."""
315 results = []
316 for (name, kind, cls, value) in inspect.classify_class_attrs(object):
317 if inspect.isdatadescriptor(value):
318 kind = 'data descriptor'
319 if isinstance(value, property) and value.fset is None:
320 kind = 'readonly property'
321 elif kind == 'method' and _is_bound_method(value):
322 kind = 'static method'
323 results.append((name, kind, cls, value))
324 return results
325
326 def sort_attributes(attrs, object):
327 'Sort the attrs list in-place by _fields and then alphabetically by name'
328 # This allows data descriptors to be ordered according
329 # to a _fields attribute if present.
330 fields = getattr(object, '_fields', [])
331 try:
332 field_order = {name : i-len(fields) for (i, name) in enumerate(fields)}
333 except TypeError:
334 field_order = {}
335 keyfunc = lambda attr: (field_order.get(attr[0], 0), attr[0])
336 attrs.sort(key=keyfunc)
337
338 # ----------------------------------------------------- module manipulation
339
340 def ispackage(path):
341 """Guess whether a path refers to a package directory."""
342 if os.path.isdir(path):
343 for ext in ('.py', '.pyc'):
344 if os.path.isfile(os.path.join(path, '__init__' + ext)):
345 return True
346 return False
347
348 def source_synopsis(file):
349 line = file.readline()
350 while line[:1] == '#' or not line.strip():
351 line = file.readline()
352 if not line: break
353 line = line.strip()
354 if line[:4] == 'r"""': line = line[1:]
355 if line[:3] == '"""':
356 line = line[3:]
357 if line[-1:] == '\\': line = line[:-1]
358 while not line.strip():
359 line = file.readline()
360 if not line: break
361 result = line.split('"""')[0].strip()
362 else: result = None
363 return result
364
365 def synopsis(filename, cache={}):
366 """Get the one-line summary out of a module file."""
367 mtime = os.stat(filename).st_mtime
368 lastupdate, result = cache.get(filename, (None, None))
369 if lastupdate is None or lastupdate < mtime:
370 # Look for binary suffixes first, falling back to source.
371 if filename.endswith(tuple(importlib.machinery.BYTECODE_SUFFIXES)):
372 loader_cls = importlib.machinery.SourcelessFileLoader
373 elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
374 loader_cls = importlib.machinery.ExtensionFileLoader
375 else:
376 loader_cls = None
377 # Now handle the choice.
378 if loader_cls is None:
379 # Must be a source file.
380 try:
381 file = tokenize.open(filename)
382 except OSError:
383 # module can't be opened, so skip it
384 return None
385 # text modules can be directly examined
386 with file:
387 result = source_synopsis(file)
388 else:
389 # Must be a binary module, which has to be imported.
390 loader = loader_cls('__temp__', filename)
391 # XXX We probably don't need to pass in the loader here.
392 spec = importlib.util.spec_from_file_location('__temp__', filename,
393 loader=loader)
394 try:
395 module = importlib._bootstrap._load(spec)
396 except:
397 return None
398 del sys.modules['__temp__']
399 result = module.__doc__.splitlines()[0] if module.__doc__ else None
400 # Cache the result.
401 cache[filename] = (mtime, result)
402 return result
403
404 class ErrorDuringImport(Exception):
405 """Errors that occurred while trying to import something to document it."""
406 def __init__(self, filename, exc_info):
407 self.filename = filename
408 self.exc, self.value, self.tb = exc_info
409
410 def __str__(self):
411 exc = self.exc.__name__
412 return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
413
414 def importfile(path):
415 """Import a Python source file or compiled file given its path."""
416 magic = importlib.util.MAGIC_NUMBER
417 with open(path, 'rb') as file:
418 is_bytecode = magic == file.read(len(magic))
419 filename = os.path.basename(path)
420 name, ext = os.path.splitext(filename)
421 if is_bytecode:
422 loader = importlib._bootstrap_external.SourcelessFileLoader(name, path)
423 else:
424 loader = importlib._bootstrap_external.SourceFileLoader(name, path)
425 # XXX We probably don't need to pass in the loader here.
426 spec = importlib.util.spec_from_file_location(name, path, loader=loader)
427 try:
428 return importlib._bootstrap._load(spec)
429 except:
430 raise ErrorDuringImport(path, sys.exc_info())
431
432 def safeimport(path, forceload=0, cache={}):
433 """Import a module; handle errors; return None if the module isn't found.
434
435 If the module *is* found but an exception occurs, it's wrapped in an
436 ErrorDuringImport exception and reraised. Unlike __import__, if a
437 package path is specified, the module at the end of the path is returned,
438 not the package at the beginning. If the optional 'forceload' argument
439 is 1, we reload the module from disk (unless it's a dynamic extension)."""
440 try:
441 # If forceload is 1 and the module has been previously loaded from
442 # disk, we always have to reload the module. Checking the file's
443 # mtime isn't good enough (e.g. the module could contain a class
444 # that inherits from another module that has changed).
445 if forceload and path in sys.modules:
446 if path not in sys.builtin_module_names:
447 # Remove the module from sys.modules and re-import to try
448 # and avoid problems with partially loaded modules.
449 # Also remove any submodules because they won't appear
450 # in the newly loaded module's namespace if they're already
451 # in sys.modules.
452 subs = [m for m in sys.modules if m.startswith(path + '.')]
453 for key in [path] + subs:
454 # Prevent garbage collection.
455 cache[key] = sys.modules[key]
456 del sys.modules[key]
457 module = __import__(path)
458 except:
459 # Did the error occur before or after the module was found?
460 (exc, value, tb) = info = sys.exc_info()
461 if path in sys.modules:
462 # An error occurred while executing the imported module.
463 raise ErrorDuringImport(sys.modules[path].__file__, info)
464 elif exc is SyntaxError:
465 # A SyntaxError occurred before we could execute the module.
466 raise ErrorDuringImport(value.filename, info)
467 elif issubclass(exc, ImportError) and value.name == path:
468 # No such module in the path.
469 return None
470 else:
471 # Some other error occurred during the importing process.
472 raise ErrorDuringImport(path, sys.exc_info())
473 for part in path.split('.')[1:]:
474 try: module = getattr(module, part)
475 except AttributeError: return None
476 return module
477
478 # ---------------------------------------------------- formatter base class
479
480 class Doc:
481
482 PYTHONDOCS = os.environ.get("PYTHONDOCS",
483 "https://docs.python.org/%d.%d/library"
484 % sys.version_info[:2])
485
486 def document(self, object, name=None, *args):
487 """Generate documentation for an object."""
488 args = (object, name) + args
489 # 'try' clause is to attempt to handle the possibility that inspect
490 # identifies something in a way that pydoc itself has issues handling;
491 # think 'super' and how it is a descriptor (which raises the exception
492 # by lacking a __name__ attribute) and an instance.
493 try:
494 if inspect.ismodule(object): return self.docmodule(*args)
495 if inspect.isclass(object): return self.docclass(*args)
496 if inspect.isroutine(object): return self.docroutine(*args)
497 except AttributeError:
498 pass
499 if inspect.isdatadescriptor(object): return self.docdata(*args)
500 return self.docother(*args)
501
502 def fail(self, object, name=None, *args):
503 """Raise an exception for unimplemented types."""
504 message = "don't know how to document object%s of type %s" % (
505 name and ' ' + repr(name), type(object).__name__)
506 raise TypeError(message)
507
508 docmodule = docclass = docroutine = docother = docproperty = docdata = fail
509
510 def getdocloc(self, object, basedir=sysconfig.get_path('stdlib')):
511 """Return the location of module docs or None"""
512
513 try:
514 file = inspect.getabsfile(object)
515 except TypeError:
516 file = '(built-in)'
517
518 docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
519
520 basedir = os.path.normcase(basedir)
521 if (isinstance(object, type(os)) and
522 (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
523 'marshal', 'posix', 'signal', 'sys',
524 '_thread', 'zipimport') or
525 (file.startswith(basedir) and
•526 not file.startswith(os.path.join(basedir, 'dist-packages')) and
527 not file.startswith(os.path.join(basedir, 'site-packages')))) and
528 object.__name__ not in ('xml.etree', 'test.test_pydoc.pydoc_mod')):
529 if docloc.startswith(("http://", "https://")):
530 docloc = "{}/{}.html".format(docloc.rstrip("/"), object.__name__.lower())
531 else:
532 docloc = os.path.join(docloc, object.__name__.lower() + ".html")
533 else:
534 docloc = None
535 return docloc
536
537 # -------------------------------------------- HTML documentation generator
538
539 class HTMLRepr(Repr):
540 """Class for safely making an HTML representation of a Python object."""
541 def __init__(self):
542 Repr.__init__(self)
543 self.maxlist = self.maxtuple = 20
544 self.maxdict = 10
545 self.maxstring = self.maxother = 100
546
547 def escape(self, text):
548 return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
549
550 def repr(self, object):
551 return Repr.repr(self, object)
552
553 def repr1(self, x, level):
554 if hasattr(type(x), '__name__'):
555 methodname = 'repr_' + '_'.join(type(x).__name__.split())
556 if hasattr(self, methodname):
557 return getattr(self, methodname)(x, level)
558 return self.escape(cram(stripid(repr(x)), self.maxother))
559
560 def repr_string(self, x, level):
561 test = cram(x, self.maxstring)
562 testrepr = repr(test)
563 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
564 # Backslashes are only literal in the string and are never
565 # needed to make any special characters, so show a raw string.
566 return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
567 return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
568 r'<span class="repr">\1</span>',
569 self.escape(testrepr))
570
571 repr_str = repr_string
572
573 def repr_instance(self, x, level):
574 try:
575 return self.escape(cram(stripid(repr(x)), self.maxstring))
576 except:
577 return self.escape('<%s instance>' % x.__class__.__name__)
578
579 repr_unicode = repr_string
580
581 class HTMLDoc(Doc):
582 """Formatter class for HTML documentation."""
583
584 # ------------------------------------------- HTML formatting utilities
585
586 _repr_instance = HTMLRepr()
587 repr = _repr_instance.repr
588 escape = _repr_instance.escape
589
590 def page(self, title, contents):
591 """Format an HTML page."""
592 return '''\
593 <!DOCTYPE html>
594 <html lang="en">
595 <head>
596 <meta charset="utf-8">
597 <title>Python: %s</title>
598 </head><body>
599 %s
600 </body></html>''' % (title, contents)
601
602 def heading(self, title, extras=''):
603 """Format a page heading."""
604 return '''
605 <table class="heading">
606 <tr class="heading-text decor">
607 <td class="title">&nbsp;<br>%s</td>
608 <td class="extra">%s</td></tr></table>
609 ''' % (title, extras or '&nbsp;')
610
611 def section(self, title, cls, contents, width=6,
612 prelude='', marginalia=None, gap='&nbsp;'):
613 """Format a section with a heading."""
614 if marginalia is None:
615 marginalia = '<span class="code">' + '&nbsp;' * width + '</span>'
616 result = '''<p>
617 <table class="section">
618 <tr class="decor %s-decor heading-text">
619 <td class="section-title" colspan=3>&nbsp;<br>%s</td></tr>
620 ''' % (cls, title)
621 if prelude:
622 result = result + '''
623 <tr><td class="decor %s-decor" rowspan=2>%s</td>
624 <td class="decor %s-decor" colspan=2>%s</td></tr>
625 <tr><td>%s</td>''' % (cls, marginalia, cls, prelude, gap)
626 else:
627 result = result + '''
628 <tr><td class="decor %s-decor">%s</td><td>%s</td>''' % (cls, marginalia, gap)
629
630 return result + '\n<td class="singlecolumn">%s</td></tr></table>' % contents
631
632 def bigsection(self, title, *args):
633 """Format a section with a big heading."""
634 title = '<strong class="bigsection">%s</strong>' % title
635 return self.section(title, *args)
636
637 def preformat(self, text):
638 """Format literal preformatted text."""
639 text = self.escape(text.expandtabs())
640 return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
641 ' ', '&nbsp;', '\n', '<br>\n')
642
643 def multicolumn(self, list, format):
644 """Format a list of items into a multi-column list."""
645 result = ''
646 rows = (len(list) + 3) // 4
647 for col in range(4):
648 result = result + '<td class="multicolumn">'
649 for i in range(rows*col, rows*col+rows):
650 if i < len(list):
651 result = result + format(list[i]) + '<br>\n'
652 result = result + '</td>'
653 return '<table><tr>%s</tr></table>' % result
654
655 def grey(self, text): return '<span class="grey">%s</span>' % text
656
657 def namelink(self, name, *dicts):
658 """Make a link for an identifier, given name-to-URL mappings."""
659 for dict in dicts:
660 if name in dict:
661 return '<a href="%s">%s</a>' % (dict[name], name)
662 return name
663
664 def classlink(self, object, modname):
665 """Make a link for a class."""
666 name, module = object.__name__, sys.modules.get(object.__module__)
667 if hasattr(module, name) and getattr(module, name) is object:
668 return '<a href="%s.html#%s">%s</a>' % (
669 module.__name__, name, classname(object, modname))
670 return classname(object, modname)
671
672 def parentlink(self, object, modname):
673 """Make a link for the enclosing class or module."""
674 link = None
675 name, module = object.__name__, sys.modules.get(object.__module__)
676 if hasattr(module, name) and getattr(module, name) is object:
677 if '.' in object.__qualname__:
678 name = object.__qualname__.rpartition('.')[0]
679 if object.__module__ != modname:
680 link = '%s.html#%s' % (module.__name__, name)
681 else:
682 link = '#%s' % name
683 else:
684 if object.__module__ != modname:
685 link = '%s.html' % module.__name__
686 if link:
687 return '<a href="%s">%s</a>' % (link, parentname(object, modname))
688 else:
689 return parentname(object, modname)
690
691 def modulelink(self, object):
692 """Make a link for a module."""
693 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
694
695 def modpkglink(self, modpkginfo):
696 """Make a link for a module or package to display in an index."""
697 name, path, ispackage, shadowed = modpkginfo
698 if shadowed:
699 return self.grey(name)
700 if path:
701 url = '%s.%s.html' % (path, name)
702 else:
703 url = '%s.html' % name
704 if ispackage:
705 text = '<strong>%s</strong>&nbsp;(package)' % name
706 else:
707 text = name
708 return '<a href="%s">%s</a>' % (url, text)
709
710 def filelink(self, url, path):
711 """Make a link to source file."""
712 return '<a href="file:%s">%s</a>' % (url, path)
713
714 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
715 """Mark up some plain text, given a context of symbols to look for.
716 Each context dictionary maps object names to anchor names."""
717 escape = escape or self.escape
718 results = []
719 here = 0
720 pattern = re.compile(r'\b((http|https|ftp)://\S+[\w/]|'
721 r'RFC[- ]?(\d+)|'
722 r'PEP[- ]?(\d+)|'
723 r'(self\.)?(\w+))')
724 while True:
725 match = pattern.search(text, here)
726 if not match: break
727 start, end = match.span()
728 results.append(escape(text[here:start]))
729
730 all, scheme, rfc, pep, selfdot, name = match.groups()
731 if scheme:
732 url = escape(all).replace('"', '&quot;')
733 results.append('<a href="%s">%s</a>' % (url, url))
734 elif rfc:
735 url = 'https://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
736 results.append('<a href="%s">%s</a>' % (url, escape(all)))
737 elif pep:
738 url = 'https://peps.python.org/pep-%04d/' % int(pep)
739 results.append('<a href="%s">%s</a>' % (url, escape(all)))
740 elif selfdot:
741 # Create a link for methods like 'self.method(...)'
742 # and use <strong> for attributes like 'self.attr'
743 if text[end:end+1] == '(':
744 results.append('self.' + self.namelink(name, methods))
745 else:
746 results.append('self.<strong>%s</strong>' % name)
747 elif text[end:end+1] == '(':
748 results.append(self.namelink(name, methods, funcs, classes))
749 else:
750 results.append(self.namelink(name, classes))
751 here = end
752 results.append(escape(text[here:]))
753 return ''.join(results)
754
755 # ---------------------------------------------- type-specific routines
756
757 def formattree(self, tree, modname, parent=None):
758 """Produce HTML for a class tree as given by inspect.getclasstree()."""
759 result = ''
760 for entry in tree:
761 if type(entry) is type(()):
762 c, bases = entry
763 result = result + '<dt class="heading-text">'
764 result = result + self.classlink(c, modname)
765 if bases and bases != (parent,):
766 parents = []
767 for base in bases:
768 parents.append(self.classlink(base, modname))
769 result = result + '(' + ', '.join(parents) + ')'
770 result = result + '\n</dt>'
771 elif type(entry) is type([]):
772 result = result + '<dd>\n%s</dd>\n' % self.formattree(
773 entry, modname, c)
774 return '<dl>\n%s</dl>\n' % result
775
776 def docmodule(self, object, name=None, mod=None, *ignored):
777 """Produce HTML documentation for a module object."""
778 name = object.__name__ # ignore the passed-in name
779 try:
780 all = object.__all__
781 except AttributeError:
782 all = None
783 parts = name.split('.')
784 links = []
785 for i in range(len(parts)-1):
786 links.append(
787 '<a href="%s.html" class="white">%s</a>' %
788 ('.'.join(parts[:i+1]), parts[i]))
789 linkedname = '.'.join(links + parts[-1:])
790 head = '<strong class="title">%s</strong>' % linkedname
791 try:
792 path = inspect.getabsfile(object)
793 url = urllib.parse.quote(path)
794 filelink = self.filelink(url, path)
795 except TypeError:
796 filelink = '(built-in)'
797 info = []
798 if hasattr(object, '__version__'):
799 version = str(object.__version__)
800 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
801 version = version[11:-1].strip()
802 info.append('version %s' % self.escape(version))
803 if hasattr(object, '__date__'):
804 info.append(self.escape(str(object.__date__)))
805 if info:
806 head = head + ' (%s)' % ', '.join(info)
807 docloc = self.getdocloc(object)
808 if docloc is not None:
809 docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals()
810 else:
811 docloc = ''
812 result = self.heading(head, '<a href=".">index</a><br>' + filelink + docloc)
813
814 #PyPy change: filter by visiblename to exclude __builtins__ (a module in PyPy, dict in CPython)
815 modules = [(k, v) for k, v in inspect.getmembers(object, inspect.ismodule)
816 if visiblename(k, all, object)]
817
818 classes, cdict = [], {}
819 for key, value in inspect.getmembers(object, inspect.isclass):
820 # if __all__ exists, believe it. Otherwise use old heuristic.
821 if (all is not None or
822 (inspect.getmodule(value) or object) is object):
823 if visiblename(key, all, object):
824 classes.append((key, value))
825 cdict[key] = cdict[value] = '#' + key
826 for key, value in classes:
827 for base in value.__bases__:
828 key, modname = base.__name__, base.__module__
829 module = sys.modules.get(modname)
830 if modname != name and module and hasattr(module, key):
831 if getattr(module, key) is base:
832 if not key in cdict:
833 cdict[key] = cdict[base] = modname + '.html#' + key
834 funcs, fdict = [], {}
835 for key, value in inspect.getmembers(object, inspect.isroutine):
836 # if __all__ exists, believe it. Otherwise use old heuristic.
837 if (all is not None or
838 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
839 if visiblename(key, all, object):
840 funcs.append((key, value))
841 fdict[key] = '#-' + key
842 if inspect.isfunction(value): fdict[value] = fdict[key]
843 data = []
844 for key, value in inspect.getmembers(object, isdata):
845 if visiblename(key, all, object):
846 data.append((key, value))
847
848 doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
849 doc = doc and '<span class="code">%s</span>' % doc
850 result = result + '<p>%s</p>\n' % doc
851
852 if hasattr(object, '__path__'):
853 modpkgs = []
854 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
855 modpkgs.append((modname, name, ispkg, 0))
856 modpkgs.sort()
857 contents = self.multicolumn(modpkgs, self.modpkglink)
858 result = result + self.bigsection(
859 'Package Contents', 'pkg-content', contents)
860 elif modules:
861 contents = self.multicolumn(
862 modules, lambda t: self.modulelink(t[1]))
863 result = result + self.bigsection(
864 'Modules', 'pkg-content', contents)
865
866 if classes:
867 classlist = [value for (key, value) in classes]
868 contents = [
869 self.formattree(inspect.getclasstree(classlist, 1), name)]
870 for key, value in classes:
871 contents.append(self.document(value, key, name, fdict, cdict))
872 result = result + self.bigsection(
873 'Classes', 'index', ' '.join(contents))
874 if funcs:
875 contents = []
876 for key, value in funcs:
877 contents.append(self.document(value, key, name, fdict, cdict))
878 result = result + self.bigsection(
879 'Functions', 'functions', ' '.join(contents))
880 if data:
881 contents = []
882 for key, value in data:
883 contents.append(self.document(value, key))
884 result = result + self.bigsection(
885 'Data', 'data', '<br>\n'.join(contents))
886 if hasattr(object, '__author__'):
887 contents = self.markup(str(object.__author__), self.preformat)
888 result = result + self.bigsection('Author', 'author', contents)
889 if hasattr(object, '__credits__'):
890 contents = self.markup(str(object.__credits__), self.preformat)
891 result = result + self.bigsection('Credits', 'credits', contents)
892
893 return result
894
895 def docclass(self, object, name=None, mod=None, funcs={}, classes={},
896 *ignored):
897 """Produce HTML documentation for a class object."""
898 realname = object.__name__
899 name = name or realname
900 bases = object.__bases__
901
902 contents = []
903 push = contents.append
904
905 # Cute little class to pump out a horizontal rule between sections.
906 class HorizontalRule:
907 def __init__(self):
908 self.needone = 0
909 def maybe(self):
910 if self.needone:
911 push('<hr>\n')
912 self.needone = 1
913 hr = HorizontalRule()
914
915 # List the mro, if non-trivial.
916 mro = deque(inspect.getmro(object))
917 if len(mro) > 2:
918 hr.maybe()
919 push('<dl><dt>Method resolution order:</dt>\n')
920 for base in mro:
921 push('<dd>%s</dd>\n' % self.classlink(base,
922 object.__module__))
923 push('</dl>\n')
924
925 def spill(msg, attrs, predicate):
926 ok, attrs = _split_list(attrs, predicate)
927 if ok:
928 hr.maybe()
929 push(msg)
930 for name, kind, homecls, value in ok:
931 try:
932 value = getattr(object, name)
933 except Exception:
934 # Some descriptors may meet a failure in their __get__.
935 # (bug #1785)
936 push(self.docdata(value, name, mod))
937 else:
938 push(self.document(value, name, mod,
939 funcs, classes, mdict, object, homecls))
940 push('\n')
941 return attrs
942
943 def spilldescriptors(msg, attrs, predicate):
944 ok, attrs = _split_list(attrs, predicate)
945 if ok:
946 hr.maybe()
947 push(msg)
948 for name, kind, homecls, value in ok:
949 push(self.docdata(value, name, mod))
950 return attrs
951
952 def spilldata(msg, attrs, predicate):
953 ok, attrs = _split_list(attrs, predicate)
954 if ok:
955 hr.maybe()
956 push(msg)
957 for name, kind, homecls, value in ok:
958 base = self.docother(getattr(object, name), name, mod)
959 doc = getdoc(value)
960 if not doc:
961 push('<dl><dt>%s</dl>\n' % base)
962 else:
963 doc = self.markup(getdoc(value), self.preformat,
964 funcs, classes, mdict)
965 doc = '<dd><span class="code">%s</span>' % doc
966 push('<dl><dt>%s%s</dl>\n' % (base, doc))
967 push('\n')
968 return attrs
969
970 attrs = [(name, kind, cls, value)
971 for name, kind, cls, value in classify_class_attrs(object)
972 if visiblename(name, obj=object)]
973
974 mdict = {}
975 for key, kind, homecls, value in attrs:
976 mdict[key] = anchor = '#' + name + '-' + key
977 try:
978 value = getattr(object, name)
979 except Exception:
980 # Some descriptors may meet a failure in their __get__.
981 # (bug #1785)
982 pass
983 try:
984 # The value may not be hashable (e.g., a data attr with
985 # a dict or list value).
986 mdict[value] = anchor
987 except TypeError:
988 pass
989
990 while attrs:
991 if mro:
992 thisclass = mro.popleft()
993 else:
994 thisclass = attrs[0][2]
995 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
996
997 if object is not builtins.object and thisclass is builtins.object:
998 attrs = inherited
999 continue
1000 elif thisclass is object:
1001 tag = 'defined here'
1002 else:
1003 tag = 'inherited from %s' % self.classlink(thisclass,
1004 object.__module__)
1005 tag += ':<br>\n'
1006
1007 sort_attributes(attrs, object)
1008
1009 # Pump out the attrs, segregated by kind.
1010 attrs = spill('Methods %s' % tag, attrs,
1011 lambda t: t[1] == 'method')
1012 attrs = spill('Class methods %s' % tag, attrs,
1013 lambda t: t[1] == 'class method')
1014 attrs = spill('Static methods %s' % tag, attrs,
1015 lambda t: t[1] == 'static method')
1016 attrs = spilldescriptors("Readonly properties %s" % tag, attrs,
1017 lambda t: t[1] == 'readonly property')
1018 attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
1019 lambda t: t[1] == 'data descriptor')
1020 attrs = spilldata('Data and other attributes %s' % tag, attrs,
1021 lambda t: t[1] == 'data')
1022 assert attrs == []
1023 attrs = inherited
1024
1025 contents = ''.join(contents)
1026
1027 if name == realname:
1028 title = '<a name="%s">class <strong>%s</strong></a>' % (
1029 name, realname)
1030 else:
1031 title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
1032 name, name, realname)
1033 if bases:
1034 parents = []
1035 for base in bases:
1036 parents.append(self.classlink(base, object.__module__))
1037 title = title + '(%s)' % ', '.join(parents)
1038
1039 decl = ''
1040 try:
1041 signature = inspect.signature(object)
1042 except (ValueError, TypeError):
1043 signature = None
1044 if signature:
1045 argspec = str(signature)
1046 if argspec and argspec != '()':
1047 decl = name + self.escape(argspec) + '\n\n'
1048
1049 doc = getdoc(object)
1050 if decl:
1051 doc = decl + (doc or '')
1052 doc = self.markup(doc, self.preformat, funcs, classes, mdict)
1053 doc = doc and '<span class="code">%s<br>&nbsp;</span>' % doc
1054
1055 return self.section(title, 'title', contents, 3, doc)
1056
1057 def formatvalue(self, object):
1058 """Format an argument default value as text."""
1059 return self.grey('=' + self.repr(object))
1060
1061 def docroutine(self, object, name=None, mod=None,
1062 funcs={}, classes={}, methods={}, cl=None, homecls=None):
1063 """Produce HTML documentation for a function or method object."""
1064 realname = object.__name__
1065 name = name or realname
1066 if homecls is None:
1067 homecls = cl
1068 anchor = ('' if cl is None else cl.__name__) + '-' + name
1069 note = ''
1070 skipdocs = False
1071 imfunc = None
1072 if _is_bound_method(object):
1073 imself = object.__self__
1074 if imself is cl:
1075 imfunc = getattr(object, '__func__', None)
1076 elif inspect.isclass(imself):
1077 note = ' class method of %s' % self.classlink(imself, mod)
1078 else:
1079 note = ' method of %s instance' % self.classlink(
1080 imself.__class__, mod)
1081 elif (inspect.ismethoddescriptor(object) or
1082 #PyPy change
1083 inspect.ismethodwrapper(object) or
1084 hasattr(object, '__objclass__')):
1085 try:
1086 objclass = object.__objclass__
1087 except AttributeError:
1088 pass
1089 else:
1090 if cl is None:
1091 note = ' unbound %s method' % self.classlink(objclass, mod)
1092 elif objclass is not homecls:
1093 note = ' from ' + self.classlink(objclass, mod)
1094 else:
1095 imfunc = object
1096 if inspect.isfunction(imfunc) and homecls is not None and (
1097 imfunc.__module__ != homecls.__module__ or
1098 imfunc.__qualname__ != homecls.__qualname__ + '.' + realname):
1099 pname = self.parentlink(imfunc, mod)
1100 if pname:
1101 note = ' from %s' % pname
1102
1103 if (inspect.iscoroutinefunction(object) or
1104 inspect.isasyncgenfunction(object)):
1105 asyncqualifier = 'async '
1106 else:
1107 asyncqualifier = ''
1108
1109 if name == realname:
1110 title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
1111 else:
1112 if (cl is not None and
1113 inspect.getattr_static(cl, realname, []) is object):
1114 reallink = '<a href="#%s">%s</a>' % (
1115 cl.__name__ + '-' + realname, realname)
1116 skipdocs = True
1117 if note.startswith(' from '):
1118 note = ''
1119 else:
1120 reallink = realname
1121 title = '<a name="%s"><strong>%s</strong></a> = %s' % (
1122 anchor, name, reallink)
1123 argspec = None
1124 if inspect.isroutine(object):
1125 try:
1126 signature = inspect.signature(object)
1127 except (ValueError, TypeError):
1128 signature = None
1129 if signature:
1130 argspec = str(signature)
1131 if realname == '<lambda>':
1132 title = '<strong>%s</strong> <em>lambda</em> ' % name
1133 # XXX lambda's won't usually have func_annotations['return']
1134 # since the syntax doesn't support but it is possible.
1135 # So removing parentheses isn't truly safe.
1136 if not object.__annotations__:
1137 argspec = argspec[1:-1] # remove parentheses
1138 if not argspec:
1139 argspec = '(...)'
1140
1141 decl = asyncqualifier + title + self.escape(argspec) + (note and
1142 self.grey('<span class="heading-text">%s</span>' % note))
1143
1144 if skipdocs:
1145 return '<dl><dt>%s</dt></dl>\n' % decl
1146 else:
1147 doc = self.markup(
1148 getdoc(object), self.preformat, funcs, classes, methods)
1149 doc = doc and '<dd><span class="code">%s</span></dd>' % doc
1150 return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
1151
1152 def docdata(self, object, name=None, mod=None, cl=None, *ignored):
1153 """Produce html documentation for a data descriptor."""
1154 results = []
1155 push = results.append
1156
1157 if name:
1158 push('<dl><dt><strong>%s</strong></dt>\n' % name)
1159 doc = self.markup(getdoc(object), self.preformat)
1160 if doc:
1161 push('<dd><span class="code">%s</span></dd>\n' % doc)
1162 push('</dl>\n')
1163
1164 return ''.join(results)
1165
1166 docproperty = docdata
1167
1168 def docother(self, object, name=None, mod=None, *ignored):
1169 """Produce HTML documentation for a data object."""
1170 lhs = name and '<strong>%s</strong> = ' % name or ''
1171 return lhs + self.repr(object)
1172
1173 def index(self, dir, shadowed=None):
1174 """Generate an HTML index for a directory of modules."""
1175 modpkgs = []
1176 if shadowed is None: shadowed = {}
1177 for importer, name, ispkg in pkgutil.iter_modules([dir]):
1178 if any((0xD800 <= ord(ch) <= 0xDFFF) for ch in name):
1179 # ignore a module if its name contains a surrogate character
1180 continue
1181 modpkgs.append((name, '', ispkg, name in shadowed))
1182 shadowed[name] = 1
1183
1184 modpkgs.sort()
1185 contents = self.multicolumn(modpkgs, self.modpkglink)
1186 return self.bigsection(dir, 'index', contents)
1187
1188 # -------------------------------------------- text documentation generator
1189
1190 class TextRepr(Repr):
1191 """Class for safely making a text representation of a Python object."""
1192 def __init__(self):
1193 Repr.__init__(self)
1194 self.maxlist = self.maxtuple = 20
1195 self.maxdict = 10
1196 self.maxstring = self.maxother = 100
1197
1198 def repr1(self, x, level):
1199 if hasattr(type(x), '__name__'):
1200 methodname = 'repr_' + '_'.join(type(x).__name__.split())
1201 if hasattr(self, methodname):
1202 return getattr(self, methodname)(x, level)
1203 return cram(stripid(repr(x)), self.maxother)
1204
1205 def repr_string(self, x, level):
1206 test = cram(x, self.maxstring)
1207 testrepr = repr(test)
1208 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
1209 # Backslashes are only literal in the string and are never
1210 # needed to make any special characters, so show a raw string.
1211 return 'r' + testrepr[0] + test + testrepr[0]
1212 return testrepr
1213
1214 repr_str = repr_string
1215
1216 def repr_instance(self, x, level):
1217 try:
1218 return cram(stripid(repr(x)), self.maxstring)
1219 except:
1220 return '<%s instance>' % x.__class__.__name__
1221
1222 class TextDoc(Doc):
1223 """Formatter class for text documentation."""
1224
1225 # ------------------------------------------- text formatting utilities
1226
1227 _repr_instance = TextRepr()
1228 repr = _repr_instance.repr
1229
1230 def bold(self, text):
1231 """Format a string in bold by overstriking."""
1232 return ''.join(ch + '\b' + ch for ch in text)
1233
1234 def indent(self, text, prefix=' '):
1235 """Indent text by prepending a given prefix to each line."""
1236 if not text: return ''
1237 lines = [prefix + line for line in text.split('\n')]
1238 if lines: lines[-1] = lines[-1].rstrip()
1239 return '\n'.join(lines)
1240
1241 def section(self, title, contents):
1242 """Format a section with a given heading."""
1243 clean_contents = self.indent(contents).rstrip()
1244 return self.bold(title) + '\n' + clean_contents + '\n\n'
1245
1246 # ---------------------------------------------- type-specific routines
1247
1248 def formattree(self, tree, modname, parent=None, prefix=''):
1249 """Render in text a class tree as returned by inspect.getclasstree()."""
1250 result = ''
1251 for entry in tree:
1252 if type(entry) is type(()):
1253 c, bases = entry
1254 result = result + prefix + classname(c, modname)
1255 if bases and bases != (parent,):
1256 parents = (classname(c, modname) for c in bases)
1257 result = result + '(%s)' % ', '.join(parents)
1258 result = result + '\n'
1259 elif type(entry) is type([]):
1260 result = result + self.formattree(
1261 entry, modname, c, prefix + ' ')
1262 return result
1263
1264 def docmodule(self, object, name=None, mod=None, *ignored):
1265 """Produce text documentation for a given module object."""
1266 name = object.__name__ # ignore the passed-in name
1267 synop, desc = splitdoc(getdoc(object))
1268 result = self.section('NAME', name + (synop and ' - ' + synop))
1269 all = getattr(object, '__all__', None)
1270 docloc = self.getdocloc(object)
1271 if docloc is not None:
1272 result = result + self.section('MODULE REFERENCE', docloc + """
1273
1274 The following documentation is automatically generated from the Python
1275 source files. It may be incomplete, incorrect or include features that
1276 are considered implementation detail and may vary between Python
1277 implementations. When in doubt, consult the module reference at the
1278 location listed above.
1279 """)
1280
1281 if desc:
1282 result = result + self.section('DESCRIPTION', desc)
1283
1284 classes = []
1285 for key, value in inspect.getmembers(object, inspect.isclass):
1286 # if __all__ exists, believe it. Otherwise use old heuristic.
1287 if (all is not None
1288 or (inspect.getmodule(value) or object) is object):
1289 if visiblename(key, all, object):
1290 classes.append((key, value))
1291 funcs = []
1292 for key, value in inspect.getmembers(object, inspect.isroutine):
1293 # if __all__ exists, believe it. Otherwise use old heuristic.
1294 if (all is not None or
1295 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
1296 if visiblename(key, all, object):
1297 funcs.append((key, value))
1298 data = []
1299 for key, value in inspect.getmembers(object, isdata):
1300 if visiblename(key, all, object):
1301 data.append((key, value))
1302
1303 modpkgs = []
1304 modpkgs_names = set()
1305 if hasattr(object, '__path__'):
1306 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
1307 modpkgs_names.add(modname)
1308 if ispkg:
1309 modpkgs.append(modname + ' (package)')
1310 else:
1311 modpkgs.append(modname)
1312
1313 modpkgs.sort()
1314 result = result + self.section(
1315 'PACKAGE CONTENTS', '\n'.join(modpkgs))
1316
1317 # Detect submodules as sometimes created by C extensions
1318 submodules = []
1319 for key, value in inspect.getmembers(object, inspect.ismodule):
1320 if value.__name__.startswith(name + '.') and key not in modpkgs_names:
1321 submodules.append(key)
1322 if submodules:
1323 submodules.sort()
1324 result = result + self.section(
1325 'SUBMODULES', '\n'.join(submodules))
1326
1327 if classes:
1328 classlist = [value for key, value in classes]
1329 contents = [self.formattree(
1330 inspect.getclasstree(classlist, 1), name)]
1331 for key, value in classes:
1332 contents.append(self.document(value, key, name))
1333 result = result + self.section('CLASSES', '\n'.join(contents))
1334
1335 if funcs:
1336 contents = []
1337 for key, value in funcs:
1338 contents.append(self.document(value, key, name))
1339 result = result + self.section('FUNCTIONS', '\n'.join(contents))
1340
1341 if data:
1342 contents = []
1343 for key, value in data:
1344 contents.append(self.docother(value, key, name, maxlen=70))
1345 result = result + self.section('DATA', '\n'.join(contents))
1346
1347 if hasattr(object, '__version__'):
1348 version = str(object.__version__)
1349 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
1350 version = version[11:-1].strip()
1351 result = result + self.section('VERSION', version)
1352 if hasattr(object, '__date__'):
1353 result = result + self.section('DATE', str(object.__date__))
1354 if hasattr(object, '__author__'):
1355 result = result + self.section('AUTHOR', str(object.__author__))
1356 if hasattr(object, '__credits__'):
1357 result = result + self.section('CREDITS', str(object.__credits__))
1358 try:
1359 file = inspect.getabsfile(object)
1360 except TypeError:
1361 file = '(built-in)'
1362 result = result + self.section('FILE', file)
1363 return result
1364
1365 def docclass(self, object, name=None, mod=None, *ignored):
1366 """Produce text documentation for a given class object."""
1367 realname = object.__name__
1368 name = name or realname
1369 bases = object.__bases__
1370
1371 def makename(c, m=object.__module__):
1372 return classname(c, m)
1373
1374 if name == realname:
1375 title = 'class ' + self.bold(realname)
1376 else:
1377 title = self.bold(name) + ' = class ' + realname
1378 if bases:
1379 parents = map(makename, bases)
1380 title = title + '(%s)' % ', '.join(parents)
1381
1382 contents = []
1383 push = contents.append
1384
1385 try:
1386 signature = inspect.signature(object)
1387 except (ValueError, TypeError):
1388 signature = None
1389 if signature:
1390 argspec = str(signature)
1391 if argspec and argspec != '()':
1392 push(name + argspec + '\n')
1393
1394 doc = getdoc(object)
1395 if doc:
1396 push(doc + '\n')
1397
1398 # List the mro, if non-trivial.
1399 mro = deque(inspect.getmro(object))
1400 if len(mro) > 2:
1401 push("Method resolution order:")
1402 for base in mro:
1403 push(' ' + makename(base))
1404 push('')
1405
1406 # List the built-in subclasses, if any:
1407 subclasses = sorted(
1408 (str(cls.__name__) for cls in type.__subclasses__(object)
1409 if not cls.__name__.startswith("_") and cls.__module__ == "builtins"),
1410 key=str.lower
1411 )
1412 no_of_subclasses = len(subclasses)
1413 MAX_SUBCLASSES_TO_DISPLAY = 4
1414 if subclasses:
1415 push("Built-in subclasses:")
1416 for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:
1417 push(' ' + subclassname)
1418 if no_of_subclasses > MAX_SUBCLASSES_TO_DISPLAY:
1419 push(' ... and ' +
1420 str(no_of_subclasses - MAX_SUBCLASSES_TO_DISPLAY) +
1421 ' other subclasses')
1422 push('')
1423
1424 # Cute little class to pump out a horizontal rule between sections.
1425 class HorizontalRule:
1426 def __init__(self):
1427 self.needone = 0
1428 def maybe(self):
1429 if self.needone:
1430 push('-' * 70)
1431 self.needone = 1
1432 hr = HorizontalRule()
1433
1434 def spill(msg, attrs, predicate):
1435 ok, attrs = _split_list(attrs, predicate)
1436 if ok:
1437 hr.maybe()
1438 push(msg)
1439 for name, kind, homecls, value in ok:
1440 try:
1441 value = getattr(object, name)
1442 except Exception:
1443 # Some descriptors may meet a failure in their __get__.
1444 # (bug #1785)
1445 push(self.docdata(value, name, mod))
1446 else:
1447 push(self.document(value,
1448 name, mod, object, homecls))
1449 return attrs
1450
1451 def spilldescriptors(msg, attrs, predicate):
1452 ok, attrs = _split_list(attrs, predicate)
1453 if ok:
1454 hr.maybe()
1455 push(msg)
1456 for name, kind, homecls, value in ok:
1457 push(self.docdata(value, name, mod))
1458 return attrs
1459
1460 def spilldata(msg, attrs, predicate):
1461 ok, attrs = _split_list(attrs, predicate)
1462 if ok:
1463 hr.maybe()
1464 push(msg)
1465 for name, kind, homecls, value in ok:
1466 doc = getdoc(value)
1467 try:
1468 obj = getattr(object, name)
1469 except AttributeError:
1470 obj = homecls.__dict__[name]
1471 push(self.docother(obj, name, mod, maxlen=70, doc=doc) +
1472 '\n')
1473 return attrs
1474
1475 attrs = [(name, kind, cls, value)
1476 for name, kind, cls, value in classify_class_attrs(object)
1477 if visiblename(name, obj=object)]
1478
1479 while attrs:
1480 if mro:
1481 thisclass = mro.popleft()
1482 else:
1483 thisclass = attrs[0][2]
1484 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
1485
1486 if object is not builtins.object and thisclass is builtins.object:
1487 attrs = inherited
1488 continue
1489 elif thisclass is object:
1490 tag = "defined here"
1491 else:
1492 tag = "inherited from %s" % classname(thisclass,
1493 object.__module__)
1494
1495 sort_attributes(attrs, object)
1496
1497 # Pump out the attrs, segregated by kind.
1498 attrs = spill("Methods %s:\n" % tag, attrs,
1499 lambda t: t[1] == 'method')
1500 attrs = spill("Class methods %s:\n" % tag, attrs,
1501 lambda t: t[1] == 'class method')
1502 attrs = spill("Static methods %s:\n" % tag, attrs,
1503 lambda t: t[1] == 'static method')
1504 attrs = spilldescriptors("Readonly properties %s:\n" % tag, attrs,
1505 lambda t: t[1] == 'readonly property')
1506 attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
1507 lambda t: t[1] == 'data descriptor')
1508 attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
1509 lambda t: t[1] == 'data')
1510
1511 assert attrs == []
1512 attrs = inherited
1513
1514 contents = '\n'.join(contents)
1515 if not contents:
1516 return title + '\n'
1517 return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n'
1518
1519 def formatvalue(self, object):
1520 """Format an argument default value as text."""
1521 return '=' + self.repr(object)
1522
1523 def docroutine(self, object, name=None, mod=None, cl=None, homecls=None):
1524 """Produce text documentation for a function or method object."""
1525 realname = object.__name__
1526 name = name or realname
1527 if homecls is None:
1528 homecls = cl
1529 note = ''
1530 skipdocs = False
1531 imfunc = None
1532 if _is_bound_method(object):
1533 imself = object.__self__
1534 if imself is cl:
1535 imfunc = getattr(object, '__func__', None)
1536 elif inspect.isclass(imself):
1537 note = ' class method of %s' % classname(imself, mod)
1538 else:
1539 note = ' method of %s instance' % classname(
1540 imself.__class__, mod)
1541 elif (inspect.ismethoddescriptor(object) or
1542 #PyPy change
1543 inspect.ismethodwrapper(object) or
1544 hasattr(object, '__objclass__')):
1545 try:
1546 objclass = object.__objclass__
1547 except AttributeError:
1548 pass
1549 else:
1550 if cl is None:
1551 note = ' unbound %s method' % classname(objclass, mod)
1552 elif objclass is not homecls:
1553 note = ' from ' + classname(objclass, mod)
1554 else:
1555 imfunc = object
1556 if inspect.isfunction(imfunc) and homecls is not None and (
1557 imfunc.__module__ != homecls.__module__ or
1558 imfunc.__qualname__ != homecls.__qualname__ + '.' + realname):
1559 pname = parentname(imfunc, mod)
1560 if pname:
1561 note = ' from %s' % pname
1562
1563 if (inspect.iscoroutinefunction(object) or
1564 inspect.isasyncgenfunction(object)):
1565 asyncqualifier = 'async '
1566 else:
1567 asyncqualifier = ''
1568
1569 if name == realname:
1570 title = self.bold(realname)
1571 else:
1572 if (cl is not None and
1573 inspect.getattr_static(cl, realname, []) is object):
1574 skipdocs = True
1575 if note.startswith(' from '):
1576 note = ''
1577 title = self.bold(name) + ' = ' + realname
1578 argspec = None
1579
1580 if inspect.isroutine(object):
1581 try:
1582 signature = inspect.signature(object)
1583 except (ValueError, TypeError):
1584 signature = None
1585 if signature:
1586 argspec = str(signature)
1587 if realname == '<lambda>':
1588 title = self.bold(name) + ' lambda '
1589 # XXX lambda's won't usually have func_annotations['return']
1590 # since the syntax doesn't support but it is possible.
1591 # So removing parentheses isn't truly safe.
1592 if not object.__annotations__:
1593 argspec = argspec[1:-1] # remove parentheses
1594 if not argspec:
1595 argspec = '(...)'
1596 decl = asyncqualifier + title + argspec + note
1597
1598 if skipdocs:
1599 return decl + '\n'
1600 else:
1601 doc = getdoc(object) or ''
1602 return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
1603
1604 def docdata(self, object, name=None, mod=None, cl=None, *ignored):
1605 """Produce text documentation for a data descriptor."""
1606 results = []
1607 push = results.append
1608
1609 if name:
1610 push(self.bold(name))
1611 push('\n')
1612 doc = getdoc(object) or ''
1613 if doc:
1614 push(self.indent(doc))
1615 push('\n')
1616 return ''.join(results)
1617
1618 docproperty = docdata
1619
1620 def docother(self, object, name=None, mod=None, parent=None, *ignored,
1621 maxlen=None, doc=None):
1622 """Produce text documentation for a data object."""
1623 repr = self.repr(object)
1624 if maxlen:
1625 line = (name and name + ' = ' or '') + repr
1626 chop = maxlen - len(line)
1627 if chop < 0: repr = repr[:chop] + '...'
1628 line = (name and self.bold(name) + ' = ' or '') + repr
1629 if not doc:
1630 doc = getdoc(object)
1631 if doc:
1632 line += '\n' + self.indent(str(doc)) + '\n'
1633 return line
1634
1635 class _PlainTextDoc(TextDoc):
1636 """Subclass of TextDoc which overrides string styling"""
1637 def bold(self, text):
1638 return text
1639
1640 # --------------------------------------------------------- user interfaces
1641
1642 def pager(text):
1643 """The first time this is called, determine what kind of pager to use."""
1644 global pager
1645 pager = getpager()
1646 pager(text)
1647
1648 def getpager():
1649 """Decide what method to use for paging through text."""
1650 if not hasattr(sys.stdin, "isatty"):
1651 return plainpager
1652 if not hasattr(sys.stdout, "isatty"):
1653 return plainpager
1654 if not sys.stdin.isatty() or not sys.stdout.isatty():
1655 return plainpager
1656 if sys.platform == "emscripten":
1657 return plainpager
1658 use_pager = os.environ.get('MANPAGER') or os.environ.get('PAGER')
1659 if use_pager:
1660 if sys.platform == 'win32': # pipes completely broken in Windows
1661 return lambda text: tempfilepager(plain(text), use_pager)
1662 elif os.environ.get('TERM') in ('dumb', 'emacs'):
1663 return lambda text: pipepager(plain(text), use_pager)
1664 else:
1665 return lambda text: pipepager(text, use_pager)
1666 if os.environ.get('TERM') in ('dumb', 'emacs'):
1667 return plainpager
1668 if sys.platform == 'win32':
1669 return lambda text: tempfilepager(plain(text), 'more <')
1670 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
1671 return lambda text: pipepager(text, 'less')
1672
1673 import tempfile
1674 (fd, filename) = tempfile.mkstemp()
1675 os.close(fd)
1676 try:
1677 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
1678 return lambda text: pipepager(text, 'more')
1679 else:
1680 return ttypager
1681 finally:
1682 os.unlink(filename)
1683
1684 def plain(text):
1685 """Remove boldface formatting from text."""
1686 return re.sub('.\b', '', text)
1687
1688 def pipepager(text, cmd):
1689 """Page through text by feeding it to another program."""
1690 import subprocess
1691 proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
1692 errors='backslashreplace')
1693 try:
1694 with proc.stdin as pipe:
1695 try:
1696 pipe.write(text)
1697 except KeyboardInterrupt:
1698 # We've hereby abandoned whatever text hasn't been written,
1699 # but the pager is still in control of the terminal.
1700 pass
1701 except OSError:
1702 pass # Ignore broken pipes caused by quitting the pager program.
1703 while True:
1704 try:
1705 proc.wait()
1706 break
1707 except KeyboardInterrupt:
1708 # Ignore ctl-c like the pager itself does. Otherwise the pager is
1709 # left running and the terminal is in raw mode and unusable.
1710 pass
1711
1712 def tempfilepager(text, cmd):
1713 """Page through text by invoking a program on a temporary file."""
1714 import tempfile
1715 with tempfile.TemporaryDirectory() as tempdir:
1716 filename = os.path.join(tempdir, 'pydoc.out')
1717 with open(filename, 'w', errors='backslashreplace',
1718 encoding=os.device_encoding(0) if
1719 sys.platform == 'win32' else None
1720 ) as file:
1721 file.write(text)
1722 os.system(cmd + ' "' + filename + '"')
1723
1724 def _escape_stdout(text):
1725 # Escape non-encodable characters to avoid encoding errors later
1726 encoding = getattr(sys.stdout, 'encoding', None) or 'utf-8'
1727 return text.encode(encoding, 'backslashreplace').decode(encoding)
1728
1729 def ttypager(text):
1730 """Page through text on a text terminal."""
1731 lines = plain(_escape_stdout(text)).split('\n')
1732 try:
1733 import tty
1734 fd = sys.stdin.fileno()
1735 old = tty.tcgetattr(fd)
1736 tty.setcbreak(fd)
1737 getchar = lambda: sys.stdin.read(1)
1738 except (ImportError, AttributeError, io.UnsupportedOperation):
1739 tty = None
1740 getchar = lambda: sys.stdin.readline()[:-1][:1]
1741
1742 try:
1743 try:
1744 h = int(os.environ.get('LINES', 0))
1745 except ValueError:
1746 h = 0
1747 if h <= 1:
1748 h = 25
1749 r = inc = h - 1
1750 sys.stdout.write('\n'.join(lines[:inc]) + '\n')
1751 while lines[r:]:
1752 sys.stdout.write('-- more --')
1753 sys.stdout.flush()
1754 c = getchar()
1755
1756 if c in ('q', 'Q'):
1757 sys.stdout.write('\r \r')
1758 break
1759 elif c in ('\r', '\n'):
1760 sys.stdout.write('\r \r' + lines[r] + '\n')
1761 r = r + 1
1762 continue
1763 if c in ('b', 'B', '\x1b'):
1764 r = r - inc - inc
1765 if r < 0: r = 0
1766 sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
1767 r = r + inc
1768
1769 finally:
1770 if tty:
1771 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
1772
1773 def plainpager(text):
1774 """Simply print unformatted text. This is the ultimate fallback."""
1775 sys.stdout.write(plain(_escape_stdout(text)))
1776
1777 def describe(thing):
1778 """Produce a short description of the given thing."""
1779 if inspect.ismodule(thing):
1780 if thing.__name__ in sys.builtin_module_names:
1781 return 'built-in module ' + thing.__name__
1782 if hasattr(thing, '__path__'):
1783 return 'package ' + thing.__name__
1784 else:
1785 return 'module ' + thing.__name__
1786 if inspect.isbuiltin(thing):
1787 return 'built-in function ' + thing.__name__
1788 if inspect.isgetsetdescriptor(thing):
1789 return 'getset descriptor %s.%s.%s' % (
1790 thing.__objclass__.__module__, thing.__objclass__.__name__,
1791 thing.__name__)
1792 if inspect.ismemberdescriptor(thing):
1793 return 'member descriptor %s.%s.%s' % (
1794 thing.__objclass__.__module__, thing.__objclass__.__name__,
1795 thing.__name__)
1796 if inspect.isclass(thing):
1797 return 'class ' + thing.__name__
1798 if inspect.isfunction(thing):
1799 return 'function ' + thing.__name__
1800 if inspect.ismethod(thing):
1801 return 'method ' + thing.__name__
1802 return type(thing).__name__
1803
1804 def locate(path, forceload=0):
1805 """Locate an object by name or dotted path, importing as necessary."""
1806 parts = [part for part in path.split('.') if part]
1807 module, n = None, 0
1808 while n < len(parts):
1809 nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
1810 if nextmodule: module, n = nextmodule, n + 1
1811 else: break
1812 if module:
1813 object = module
1814 else:
1815 object = builtins
1816 for part in parts[n:]:
1817 try:
1818 object = getattr(object, part)
1819 except AttributeError:
1820 return None
1821 return object
1822
1823 # --------------------------------------- interactive interpreter interface
1824
1825 text = TextDoc()
1826 plaintext = _PlainTextDoc()
1827 html = HTMLDoc()
1828
1829 def resolve(thing, forceload=0):
1830 """Given an object or a path to an object, get the object and its name."""
1831 if isinstance(thing, str):
1832 object = locate(thing, forceload)
1833 if object is None:
1834 raise ImportError('''\
1835 No Python documentation found for %r.
1836 Use help() to get the interactive help utility.
1837 Use help(str) for help on the str class.''' % thing)
1838 return object, thing
1839 else:
1840 name = getattr(thing, '__name__', None)
1841 return thing, name if isinstance(name, str) else None
1842
1843 def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
1844 renderer=None):
1845 """Render text documentation, given an object or a path to an object."""
1846 if renderer is None:
1847 renderer = text
1848 object, name = resolve(thing, forceload)
1849 desc = describe(object)
1850 module = inspect.getmodule(object)
1851 if name and '.' in name:
1852 desc += ' in ' + name[:name.rfind('.')]
1853 elif module and module is not object:
1854 desc += ' in module ' + module.__name__
1855
1856 if not (inspect.ismodule(object) or
1857 inspect.isclass(object) or
1858 inspect.isroutine(object) or
1859 inspect.isdatadescriptor(object) or
1860 _getdoc(object)):
1861 # If the passed object is a piece of data or an instance,
1862 # document its available methods instead of its value.
1863 if hasattr(object, '__origin__'):
1864 object = object.__origin__
1865 else:
1866 object = type(object)
1867 desc += ' object'
1868 return title % desc + '\n\n' + renderer.document(object, name)
1869
1870 def doc(thing, title='Python Library Documentation: %s', forceload=0,
1871 output=None, is_cli=False):
1872 """Display text documentation, given an object or a path to an object."""
1873 if output is None:
1874 try:
1875 pager(render_doc(thing, title, forceload))
1876 except ImportError as exc:
1877 if is_cli:
1878 raise
1879 print(exc)
1880 else:
1881 try:
1882 s = render_doc(thing, title, forceload, plaintext)
1883 except ImportError as exc:
1884 s = str(exc)
1885 output.write(s)
1886
1887 def writedoc(thing, forceload=0):
1888 """Write HTML documentation to a file in the current directory."""
1889 object, name = resolve(thing, forceload)
1890 page = html.page(describe(object), html.document(object, name))
1891 with open(name + '.html', 'w', encoding='utf-8') as file:
1892 file.write(page)
1893 print('wrote', name + '.html')
1894
1895 def writedocs(dir, pkgpath='', done=None):
1896 """Write out HTML documentation for all modules in a directory tree."""
1897 if done is None: done = {}
1898 for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
1899 writedoc(modname)
1900 return
1901
1902 class Helper:
1903
1904 # These dictionaries map a topic name to either an alias, or a tuple
1905 # (label, seealso-items). The "label" is the label of the corresponding
1906 # section in the .rst file under Doc/ and an index into the dictionary
1907 # in pydoc_data/topics.py.
1908 #
1909 # CAUTION: if you change one of these dictionaries, be sure to adapt the
1910 # list of needed labels in Doc/tools/extensions/pyspecific.py and
1911 # regenerate the pydoc_data/topics.py file by running
1912 # make pydoc-topics
1913 # in Doc/ and copying the output file into the Lib/ directory.
1914
1915 keywords = {
1916 'False': '',
1917 'None': '',
1918 'True': '',
1919 'and': 'BOOLEAN',
1920 'as': 'with',
1921 'assert': ('assert', ''),
1922 'async': ('async', ''),
1923 'await': ('await', ''),
1924 'break': ('break', 'while for'),
1925 'class': ('class', 'CLASSES SPECIALMETHODS'),
1926 'continue': ('continue', 'while for'),
1927 'def': ('function', ''),
1928 'del': ('del', 'BASICMETHODS'),
1929 'elif': 'if',
1930 'else': ('else', 'while for'),
1931 'except': 'try',
1932 'finally': 'try',
1933 'for': ('for', 'break continue while'),
1934 'from': 'import',
1935 'global': ('global', 'nonlocal NAMESPACES'),
1936 'if': ('if', 'TRUTHVALUE'),
1937 'import': ('import', 'MODULES'),
1938 'in': ('in', 'SEQUENCEMETHODS'),
1939 'is': 'COMPARISON',
1940 'lambda': ('lambda', 'FUNCTIONS'),
1941 'nonlocal': ('nonlocal', 'global NAMESPACES'),
1942 'not': 'BOOLEAN',
1943 'or': 'BOOLEAN',
1944 'pass': ('pass', ''),
1945 'raise': ('raise', 'EXCEPTIONS'),
1946 'return': ('return', 'FUNCTIONS'),
1947 'try': ('try', 'EXCEPTIONS'),
1948 'while': ('while', 'break continue if TRUTHVALUE'),
1949 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
1950 'yield': ('yield', ''),
1951 }
1952 # Either add symbols to this dictionary or to the symbols dictionary
1953 # directly: Whichever is easier. They are merged later.
1954 _strprefixes = [p + q for p in ('b', 'f', 'r', 'u') for q in ("'", '"')]
1955 _symbols_inverse = {
1956 'STRINGS' : ("'", "'''", '"', '"""', *_strprefixes),
1957 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
1958 '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
1959 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
1960 'UNARY' : ('-', '~'),
1961 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
1962 '^=', '<<=', '>>=', '**=', '//='),
1963 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
1964 'COMPLEX' : ('j', 'J')
1965 }
1966 symbols = {
1967 '%': 'OPERATORS FORMATTING',
1968 '**': 'POWER',
1969 ',': 'TUPLES LISTS FUNCTIONS',
1970 '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
1971 '...': 'ELLIPSIS',
1972 ':': 'SLICINGS DICTIONARYLITERALS',
1973 '@': 'def class',
1974 '\\': 'STRINGS',
1975 '_': 'PRIVATENAMES',
1976 '__': 'PRIVATENAMES SPECIALMETHODS',
1977 '`': 'BACKQUOTES',
1978 '(': 'TUPLES FUNCTIONS CALLS',
1979 ')': 'TUPLES FUNCTIONS CALLS',
1980 '[': 'LISTS SUBSCRIPTS SLICINGS',
1981 ']': 'LISTS SUBSCRIPTS SLICINGS'
1982 }
1983 for topic, symbols_ in _symbols_inverse.items():
1984 for symbol in symbols_:
1985 topics = symbols.get(symbol, topic)
1986 if topic not in topics:
1987 topics = topics + ' ' + topic
1988 symbols[symbol] = topics
1989 del topic, symbols_, symbol, topics
1990
1991 topics = {
1992 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
1993 'FUNCTIONS CLASSES MODULES FILES inspect'),
1994 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS '
1995 'FORMATTING TYPES'),
1996 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
1997 'FORMATTING': ('formatstrings', 'OPERATORS'),
1998 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
1999 'FORMATTING TYPES'),
2000 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
2001 'INTEGER': ('integers', 'int range'),
2002 'FLOAT': ('floating', 'float math'),
2003 'COMPLEX': ('imaginary', 'complex cmath'),
2004 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
2005 'MAPPINGS': 'DICTIONARIES',
2006 'FUNCTIONS': ('typesfunctions', 'def TYPES'),
2007 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
2008 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
2009 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
2010 'FRAMEOBJECTS': 'TYPES',
2011 'TRACEBACKS': 'TYPES',
2012 'NONE': ('bltin-null-object', ''),
2013 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
2014 'SPECIALATTRIBUTES': ('specialattrs', ''),
2015 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
2016 'MODULES': ('typesmodules', 'import'),
2017 'PACKAGES': 'import',
2018 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
2019 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
2020 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
2021 'LISTS DICTIONARIES'),
2022 'OPERATORS': 'EXPRESSIONS',
2023 'PRECEDENCE': 'EXPRESSIONS',
2024 'OBJECTS': ('objects', 'TYPES'),
2025 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
2026 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '
2027 'NUMBERMETHODS CLASSES'),
2028 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'),
2029 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
2030 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
2031 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS '
2032 'SPECIALMETHODS'),
2033 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
2034 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
2035 'SPECIALMETHODS'),
2036 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
2037 'NAMESPACES': ('naming', 'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),
2038 'DYNAMICFEATURES': ('dynamic-features', ''),
2039 'SCOPING': 'NAMESPACES',
2040 'FRAMES': 'NAMESPACES',
2041 'EXCEPTIONS': ('exceptions', 'try except finally raise'),
2042 'CONVERSIONS': ('conversions', ''),
2043 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
2044 'SPECIALIDENTIFIERS': ('id-classes', ''),
2045 'PRIVATENAMES': ('atom-identifiers', ''),
2046 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS '
2047 'LISTLITERALS DICTIONARYLITERALS'),
2048 'TUPLES': 'SEQUENCES',
2049 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
2050 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
2051 'LISTLITERALS': ('lists', 'LISTS LITERALS'),
2052 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
2053 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
2054 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
2055 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'),
2056 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'),
2057 'CALLS': ('calls', 'EXPRESSIONS'),
2058 'POWER': ('power', 'EXPRESSIONS'),
2059 'UNARY': ('unary', 'EXPRESSIONS'),
2060 'BINARY': ('binary', 'EXPRESSIONS'),
2061 'SHIFTING': ('shifting', 'EXPRESSIONS'),
2062 'BITWISE': ('bitwise', 'EXPRESSIONS'),
2063 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
2064 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
2065 'ASSERTION': 'assert',
2066 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
2067 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
2068 'DELETION': 'del',
2069 'RETURNING': 'return',
2070 'IMPORTING': 'import',
2071 'CONDITIONAL': 'if',
2072 'LOOPING': ('compound', 'for while break continue'),
2073 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
2074 'DEBUGGING': ('debugger', 'pdb'),
2075 'CONTEXTMANAGERS': ('context-managers', 'with'),
2076 }
2077
2078 def __init__(self, input=None, output=None):
2079 self._input = input
2080 self._output = output
2081
2082 @property
2083 def input(self):
2084 return self._input or sys.stdin
2085
2086 @property
2087 def output(self):
2088 return self._output or sys.stdout
2089
2090 def __repr__(self):
2091 if inspect.stack()[1][3] == '?':
2092 self()
2093 return ''
2094 return '<%s.%s instance>' % (self.__class__.__module__,
2095 self.__class__.__qualname__)
2096
2097 _GoInteractive = object()
2098 def __call__(self, request=_GoInteractive):
2099 if request is not self._GoInteractive:
2100 try:
2101 self.help(request)
2102 except ImportError as e:
2103 self.output.write(f'{e}\n')
2104 else:
2105 self.intro()
2106 self.interact()
2107 self.output.write('''
2108 You are now leaving help and returning to the Python interpreter.
2109 If you want to ask for help on a particular object directly from the
2110 interpreter, you can type "help(object)". Executing "help('string')"
2111 has the same effect as typing a particular string at the help> prompt.
2112 ''')
2113
2114 def interact(self):
2115 self.output.write('\n')
2116 while True:
2117 try:
2118 request = self.getline('help> ')
2119 if not request: break
2120 except (KeyboardInterrupt, EOFError):
2121 break
2122 request = request.strip()
2123
2124 # Make sure significant trailing quoting marks of literals don't
2125 # get deleted while cleaning input
2126 if (len(request) > 2 and request[0] == request[-1] in ("'", '"')
2127 and request[0] not in request[1:-1]):
2128 request = request[1:-1]
2129 if request.lower() in ('q', 'quit'): break
2130 if request == 'help':
2131 self.intro()
2132 else:
2133 self.help(request)
2134
2135 def getline(self, prompt):
2136 """Read one line, using input() when appropriate."""
2137 if self.input is sys.stdin:
2138 return input(prompt)
2139 else:
2140 self.output.write(prompt)
2141 self.output.flush()
2142 return self.input.readline()
2143
2144 def help(self, request, is_cli=False):
2145 if isinstance(request, str):
2146 request = request.strip()
2147 if request == 'keywords': self.listkeywords()
2148 elif request == 'symbols': self.listsymbols()
2149 elif request == 'topics': self.listtopics()
2150 elif request == 'modules': self.listmodules()
2151 elif request[:8] == 'modules ':
2152 self.listmodules(request.split()[1])
2153 elif request in self.symbols: self.showsymbol(request)
2154 elif request in ['True', 'False', 'None']:
2155 # special case these keywords since they are objects too
2156 doc(eval(request), 'Help on %s:', is_cli=is_cli)
2157 elif request in self.keywords: self.showtopic(request)
2158 elif request in self.topics: self.showtopic(request)
2159 elif request: doc(request, 'Help on %s:', output=self._output, is_cli=is_cli)
2160 else: doc(str, 'Help on %s:', output=self._output, is_cli=is_cli)
2161 elif isinstance(request, Helper): self()
2162 else: doc(request, 'Help on %s:', output=self._output, is_cli=is_cli)
2163 self.output.write('\n')
2164
2165 def intro(self):
2166 self.output.write('''\
2167 Welcome to Python {0}'s help utility! If this is your first time using
2168 Python, you should definitely check out the tutorial at
2169 https://docs.python.org/{0}/tutorial/.
2170
2171 Enter the name of any module, keyword, or topic to get help on writing
2172 Python programs and using Python modules. To get a list of available
2173 modules, keywords, symbols, or topics, enter "modules", "keywords",
2174 "symbols", or "topics".
2175
2176 Each module also comes with a one-line summary of what it does; to list
2177 the modules whose name or summary contain a given string such as "spam",
2178 enter "modules spam".
2179
2180 To quit this help utility and return to the interpreter,
2181 enter "q" or "quit".
2182 '''.format('%d.%d' % sys.version_info[:2]))
2183
2184 def list(self, items, columns=4, width=80):
2185 items = list(sorted(items))
2186 colw = width // columns
2187 rows = (len(items) + columns - 1) // columns
2188 for row in range(rows):
2189 for col in range(columns):
2190 i = col * rows + row
2191 if i < len(items):
2192 self.output.write(items[i])
2193 if col < columns - 1:
2194 self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
2195 self.output.write('\n')
2196
2197 def listkeywords(self):
2198 self.output.write('''
2199 Here is a list of the Python keywords. Enter any keyword to get more help.
2200
2201 ''')
2202 self.list(self.keywords.keys())
2203
2204 def listsymbols(self):
2205 self.output.write('''
2206 Here is a list of the punctuation symbols which Python assigns special meaning
2207 to. Enter any symbol to get more help.
2208
2209 ''')
2210 self.list(self.symbols.keys())
2211
2212 def listtopics(self):
2213 self.output.write('''
2214 Here is a list of available topics. Enter any topic name to get more help.
2215
2216 ''')
2217 self.list(self.topics.keys())
2218
2219 def showtopic(self, topic, more_xrefs=''):
2220 try:
2221 import pydoc_data.topics
2222 except ImportError:
2223 self.output.write('''
2224 Sorry, topic and keyword documentation is not available because the
2225 module "pydoc_data.topics" could not be found.
2226 ''')
2227 return
2228 target = self.topics.get(topic, self.keywords.get(topic))
2229 if not target:
2230 self.output.write('no documentation found for %s\n' % repr(topic))
2231 return
2232 if type(target) is type(''):
2233 return self.showtopic(target, more_xrefs)
2234
2235 label, xrefs = target
2236 try:
2237 doc = pydoc_data.topics.topics[label]
2238 except KeyError:
2239 self.output.write('no documentation found for %s\n' % repr(topic))
2240 return
2241 doc = doc.strip() + '\n'
2242 if more_xrefs:
2243 xrefs = (xrefs or '') + ' ' + more_xrefs
2244 if xrefs:
2245 import textwrap
2246 text = 'Related help topics: ' + ', '.join(xrefs.split()) + '\n'
2247 wrapped_text = textwrap.wrap(text, 72)
2248 doc += '\n%s\n' % '\n'.join(wrapped_text)
2249 pager(doc)
2250
2251 def _gettopic(self, topic, more_xrefs=''):
2252 """Return unbuffered tuple of (topic, xrefs).
2253
2254 If an error occurs here, the exception is caught and displayed by
2255 the url handler.
2256
2257 This function duplicates the showtopic method but returns its
2258 result directly so it can be formatted for display in an html page.
2259 """
2260 try:
2261 import pydoc_data.topics
2262 except ImportError:
2263 return('''
2264 Sorry, topic and keyword documentation is not available because the
2265 module "pydoc_data.topics" could not be found.
2266 ''' , '')
2267 target = self.topics.get(topic, self.keywords.get(topic))
2268 if not target:
2269 raise ValueError('could not find topic')
2270 if isinstance(target, str):
2271 return self._gettopic(target, more_xrefs)
2272 label, xrefs = target
2273 doc = pydoc_data.topics.topics[label]
2274 if more_xrefs:
2275 xrefs = (xrefs or '') + ' ' + more_xrefs
2276 return doc, xrefs
2277
2278 def showsymbol(self, symbol):
2279 target = self.symbols[symbol]
2280 topic, _, xrefs = target.partition(' ')
2281 self.showtopic(topic, xrefs)
2282
2283 def listmodules(self, key=''):
2284 if key:
2285 self.output.write('''
2286 Here is a list of modules whose name or summary contains '{}'.
2287 If there are any, enter a module name to get more help.
2288
2289 '''.format(key))
2290 apropos(key)
2291 else:
2292 self.output.write('''
2293 Please wait a moment while I gather a list of all available modules...
2294
2295 ''')
2296 modules = {}
2297 def callback(path, modname, desc, modules=modules):
2298 if modname and modname[-9:] == '.__init__':
2299 modname = modname[:-9] + ' (package)'
2300 if modname.find('.') < 0:
2301 modules[modname] = 1
2302 def onerror(modname):
2303 callback(None, modname, None)
2304 ModuleScanner().run(callback, onerror=onerror)
2305 self.list(modules.keys())
2306 self.output.write('''
2307 Enter any module name to get more help. Or, type "modules spam" to search
2308 for modules whose name or summary contain the string "spam".
2309 ''')
2310
2311 help = Helper()
2312
2313 class ModuleScanner:
2314 """An interruptible scanner that searches module synopses."""
2315
2316 def run(self, callback, key=None, completer=None, onerror=None):
2317 if key: key = key.lower()
2318 self.quit = False
2319 seen = {}
2320
2321 for modname in sys.builtin_module_names:
2322 if modname != '__main__':
2323 seen[modname] = 1
2324 if key is None:
2325 callback(None, modname, '')
2326 else:
2327 name = __import__(modname).__doc__ or ''
2328 desc = name.split('\n')[0]
2329 name = modname + ' - ' + desc
2330 if name.lower().find(key) >= 0:
2331 callback(None, modname, desc)
2332
2333 for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
2334 if self.quit:
2335 break
2336
2337 if key is None:
2338 callback(None, modname, '')
2339 else:
2340 try:
2341 spec = pkgutil._get_spec(importer, modname)
2342 except SyntaxError:
2343 # raised by tests for bad coding cookies or BOM
2344 continue
2345 loader = spec.loader
2346 if hasattr(loader, 'get_source'):
2347 try:
2348 source = loader.get_source(modname)
2349 except Exception:
2350 if onerror:
2351 onerror(modname)
2352 continue
2353 desc = source_synopsis(io.StringIO(source)) or ''
2354 if hasattr(loader, 'get_filename'):
2355 path = loader.get_filename(modname)
2356 else:
2357 path = None
2358 else:
2359 try:
2360 module = importlib._bootstrap._load(spec)
2361 except ImportError:
2362 if onerror:
2363 onerror(modname)
2364 continue
2365 desc = module.__doc__.splitlines()[0] if module.__doc__ else ''
2366 path = getattr(module,'__file__',None)
2367 name = modname + ' - ' + desc
2368 if name.lower().find(key) >= 0:
2369 callback(path, modname, desc)
2370
2371 if completer:
2372 completer()
2373
2374 def apropos(key):
2375 """Print all the one-line module summaries that contain a substring."""
2376 def callback(path, modname, desc):
2377 if modname[-9:] == '.__init__':
2378 modname = modname[:-9] + ' (package)'
2379 print(modname, desc and '- ' + desc)
2380 def onerror(modname):
2381 pass
2382 with warnings.catch_warnings():
2383 warnings.filterwarnings('ignore') # ignore problems during import
2384 ModuleScanner().run(callback, key, onerror=onerror)
2385
2386 # --------------------------------------- enhanced web browser interface
2387
2388 def _start_server(urlhandler, hostname, port):
2389 """Start an HTTP server thread on a specific port.
2390
2391 Start an HTML/text server thread, so HTML or text documents can be
2392 browsed dynamically and interactively with a web browser. Example use:
2393
2394 >>> import time
2395 >>> import pydoc
2396
2397 Define a URL handler. To determine what the client is asking
2398 for, check the URL and content_type.
2399
2400 Then get or generate some text or HTML code and return it.
2401
2402 >>> def my_url_handler(url, content_type):
2403 ... text = 'the URL sent was: (%s, %s)' % (url, content_type)
2404 ... return text
2405
2406 Start server thread on port 0.
2407 If you use port 0, the server will pick a random port number.
2408 You can then use serverthread.port to get the port number.
2409
2410 >>> port = 0
2411 >>> serverthread = pydoc._start_server(my_url_handler, port)
2412
2413 Check that the server is really started. If it is, open browser
2414 and get first page. Use serverthread.url as the starting page.
2415
2416 >>> if serverthread.serving:
2417 ... import webbrowser
2418
2419 The next two lines are commented out so a browser doesn't open if
2420 doctest is run on this module.
2421
2422 #... webbrowser.open(serverthread.url)
2423 #True
2424
2425 Let the server do its thing. We just need to monitor its status.
2426 Use time.sleep so the loop doesn't hog the CPU.
2427
2428 >>> starttime = time.monotonic()
2429 >>> timeout = 1 #seconds
2430
2431 This is a short timeout for testing purposes.
2432
2433 >>> while serverthread.serving:
2434 ... time.sleep(.01)
2435 ... if serverthread.serving and time.monotonic() - starttime > timeout:
2436 ... serverthread.stop()
2437 ... break
2438
2439 Print any errors that may have occurred.
2440
2441 >>> print(serverthread.error)
2442 None
2443 """
2444 import http.server
2445 import email.message
2446 import select
2447 import threading
2448
2449 class DocHandler(http.server.BaseHTTPRequestHandler):
2450
2451 def do_GET(self):
2452 """Process a request from an HTML browser.
2453
2454 The URL received is in self.path.
2455 Get an HTML page from self.urlhandler and send it.
2456 """
2457 if self.path.endswith('.css'):
2458 content_type = 'text/css'
2459 else:
2460 content_type = 'text/html'
2461 self.send_response(200)
2462 self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
2463 self.end_headers()
2464 self.wfile.write(self.urlhandler(
2465 self.path, content_type).encode('utf-8'))
2466
2467 def log_message(self, *args):
2468 # Don't log messages.
2469 pass
2470
2471 class DocServer(http.server.HTTPServer):
2472
2473 def __init__(self, host, port, callback):
2474 self.host = host
2475 self.address = (self.host, port)
2476 self.callback = callback
2477 self.base.__init__(self, self.address, self.handler)
2478 self.quit = False
2479
2480 def serve_until_quit(self):
2481 while not self.quit:
2482 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
2483 if rd:
2484 self.handle_request()
2485 self.server_close()
2486
2487 def server_activate(self):
2488 self.base.server_activate(self)
2489 if self.callback:
2490 self.callback(self)
2491
2492 class ServerThread(threading.Thread):
2493
2494 def __init__(self, urlhandler, host, port):
2495 self.urlhandler = urlhandler
2496 self.host = host
2497 self.port = int(port)
2498 threading.Thread.__init__(self)
2499 self.serving = False
2500 self.error = None
2501 self.docserver = None
2502
2503 def run(self):
2504 """Start the server."""
2505 try:
2506 DocServer.base = http.server.HTTPServer
2507 DocServer.handler = DocHandler
2508 DocHandler.MessageClass = email.message.Message
2509 DocHandler.urlhandler = staticmethod(self.urlhandler)
2510 docsvr = DocServer(self.host, self.port, self.ready)
2511 self.docserver = docsvr
2512 docsvr.serve_until_quit()
2513 except Exception as e:
2514 self.error = e
2515
2516 def ready(self, server):
2517 self.serving = True
2518 self.host = server.host
2519 self.port = server.server_port
2520 self.url = 'http://%s:%d/' % (self.host, self.port)
2521
2522 def stop(self):
2523 """Stop the server and this thread nicely"""
2524 self.docserver.quit = True
2525 self.join()
2526 # explicitly break a reference cycle: DocServer.callback
2527 # has indirectly a reference to ServerThread.
2528 self.docserver = None
2529 self.serving = False
2530 self.url = None
2531
2532 thread = ServerThread(urlhandler, hostname, port)
2533 thread.start()
2534 # Wait until thread.serving is True and thread.docserver is set
2535 # to make sure we are really up before returning.
2536 while not thread.error and not (thread.serving and thread.docserver):
2537 time.sleep(.01)
2538 return thread
2539
2540
2541 def _url_handler(url, content_type="text/html"):
2542 """The pydoc url handler for use with the pydoc server.
2543
2544 If the content_type is 'text/css', the _pydoc.css style
2545 sheet is read and returned if it exits.
2546
2547 If the content_type is 'text/html', then the result of
2548 get_html_page(url) is returned.
2549 """
2550 class _HTMLDoc(HTMLDoc):
2551
2552 def page(self, title, contents):
2553 """Format an HTML page."""
2554 css_path = "pydoc_data/_pydoc.css"
2555 css_link = (
2556 '<link rel="stylesheet" type="text/css" href="%s">' %
2557 css_path)
2558 return '''\
2559 <!DOCTYPE>
2560 <html lang="en">
2561 <head>
2562 <meta charset="utf-8">
2563 <title>Pydoc: %s</title>
2564 %s</head><body>%s<div style="clear:both;padding-top:.5em;">%s</div>
2565 </body></html>''' % (title, css_link, html_navbar(), contents)
2566
2567
2568 html = _HTMLDoc()
2569
2570 def html_navbar():
2571 version = html.escape("%s [%s, %s]" % (platform.python_version(),
2572 platform.python_build()[0],
2573 platform.python_compiler()))
2574 return """
2575 <div style='float:left'>
2576 Python %s<br>%s
2577 </div>
2578 <div style='float:right'>
2579 <div style='text-align:center'>
2580 <a href="index.html">Module Index</a>
2581 : <a href="topics.html">Topics</a>
2582 : <a href="keywords.html">Keywords</a>
2583 </div>
2584 <div>
2585 <form action="get" style='display:inline;'>
2586 <input type=text name=key size=15>
2587 <input type=submit value="Get">
2588 </form>&nbsp;
2589 <form action="search" style='display:inline;'>
2590 <input type=text name=key size=15>
2591 <input type=submit value="Search">
2592 </form>
2593 </div>
2594 </div>
2595 """ % (version, html.escape(platform.platform(terse=True)))
2596
2597 def html_index():
2598 """Module Index page."""
2599
2600 def bltinlink(name):
2601 return '<a href="%s.html">%s</a>' % (name, name)
2602
2603 heading = html.heading(
2604 '<strong class="title">Index of Modules</strong>'
2605 )
2606 names = [name for name in sys.builtin_module_names
2607 if name != '__main__']
2608 contents = html.multicolumn(names, bltinlink)
2609 contents = [heading, '<p>' + html.bigsection(
2610 'Built-in Modules', 'index', contents)]
2611
2612 seen = {}
2613 for dir in sys.path:
2614 contents.append(html.index(dir, seen))
2615
2616 contents.append(
2617 '<p align=right class="heading-text grey"><strong>pydoc</strong> by Ka-Ping Yee'
2618 '&lt;[email protected]&gt;</p>')
2619 return 'Index of Modules', ''.join(contents)
2620
2621 def html_search(key):
2622 """Search results page."""
2623 # scan for modules
2624 search_result = []
2625
2626 def callback(path, modname, desc):
2627 if modname[-9:] == '.__init__':
2628 modname = modname[:-9] + ' (package)'
2629 search_result.append((modname, desc and '- ' + desc))
2630
2631 with warnings.catch_warnings():
2632 warnings.filterwarnings('ignore') # ignore problems during import
2633 def onerror(modname):
2634 pass
2635 ModuleScanner().run(callback, key, onerror=onerror)
2636
2637 # format page
2638 def bltinlink(name):
2639 return '<a href="%s.html">%s</a>' % (name, name)
2640
2641 results = []
2642 heading = html.heading(
2643 '<strong class="title">Search Results</strong>',
2644 )
2645 for name, desc in search_result:
2646 results.append(bltinlink(name) + desc)
2647 contents = heading + html.bigsection(
2648 'key = %s' % key, 'index', '<br>'.join(results))
2649 return 'Search Results', contents
2650
2651 def html_topics():
2652 """Index of topic texts available."""
2653
2654 def bltinlink(name):
2655 return '<a href="topic?key=%s">%s</a>' % (name, name)
2656
2657 heading = html.heading(
2658 '<strong class="title">INDEX</strong>',
2659 )
2660 names = sorted(Helper.topics.keys())
2661
2662 contents = html.multicolumn(names, bltinlink)
2663 contents = heading + html.bigsection(
2664 'Topics', 'index', contents)
2665 return 'Topics', contents
2666
2667 def html_keywords():
2668 """Index of keywords."""
2669 heading = html.heading(
2670 '<strong class="title">INDEX</strong>',
2671 )
2672 names = sorted(Helper.keywords.keys())
2673
2674 def bltinlink(name):
2675 return '<a href="topic?key=%s">%s</a>' % (name, name)
2676
2677 contents = html.multicolumn(names, bltinlink)
2678 contents = heading + html.bigsection(
2679 'Keywords', 'index', contents)
2680 return 'Keywords', contents
2681
2682 def html_topicpage(topic):
2683 """Topic or keyword help page."""
2684 buf = io.StringIO()
2685 htmlhelp = Helper(buf, buf)
2686 contents, xrefs = htmlhelp._gettopic(topic)
2687 if topic in htmlhelp.keywords:
2688 title = 'KEYWORD'
2689 else:
2690 title = 'TOPIC'
2691 heading = html.heading(
2692 '<strong class="title">%s</strong>' % title,
2693 )
2694 contents = '<pre>%s</pre>' % html.markup(contents)
2695 contents = html.bigsection(topic , 'index', contents)
2696 if xrefs:
2697 xrefs = sorted(xrefs.split())
2698
2699 def bltinlink(name):
2700 return '<a href="topic?key=%s">%s</a>' % (name, name)
2701
2702 xrefs = html.multicolumn(xrefs, bltinlink)
2703 xrefs = html.section('Related help topics: ', 'index', xrefs)
2704 return ('%s %s' % (title, topic),
2705 ''.join((heading, contents, xrefs)))
2706
2707 def html_getobj(url):
2708 obj = locate(url, forceload=1)
2709 if obj is None and url != 'None':
2710 raise ValueError('could not find object')
2711 title = describe(obj)
2712 content = html.document(obj, url)
2713 return title, content
2714
2715 def html_error(url, exc):
2716 heading = html.heading(
2717 '<strong class="title">Error</strong>',
2718 )
2719 contents = '<br>'.join(html.escape(line) for line in
2720 format_exception_only(type(exc), exc))
2721 contents = heading + html.bigsection(url, 'error', contents)
2722 return "Error - %s" % url, contents
2723
2724 def get_html_page(url):
2725 """Generate an HTML page for url."""
2726 complete_url = url
2727 if url.endswith('.html'):
2728 url = url[:-5]
2729 try:
2730 if url in ("", "index"):
2731 title, content = html_index()
2732 elif url == "topics":
2733 title, content = html_topics()
2734 elif url == "keywords":
2735 title, content = html_keywords()
2736 elif '=' in url:
2737 op, _, url = url.partition('=')
2738 if op == "search?key":
2739 title, content = html_search(url)
2740 elif op == "topic?key":
2741 # try topics first, then objects.
2742 try:
2743 title, content = html_topicpage(url)
2744 except ValueError:
2745 title, content = html_getobj(url)
2746 elif op == "get?key":
2747 # try objects first, then topics.
2748 if url in ("", "index"):
2749 title, content = html_index()
2750 else:
2751 try:
2752 title, content = html_getobj(url)
2753 except ValueError:
2754 title, content = html_topicpage(url)
2755 else:
2756 raise ValueError('bad pydoc url')
2757 else:
2758 title, content = html_getobj(url)
2759 except Exception as exc:
2760 # Catch any errors and display them in an error page.
2761 title, content = html_error(complete_url, exc)
2762 return html.page(title, content)
2763
2764 if url.startswith('/'):
2765 url = url[1:]
2766 if content_type == 'text/css':
2767 path_here = os.path.dirname(os.path.realpath(__file__))
2768 css_path = os.path.join(path_here, url)
2769 with open(css_path) as fp:
2770 return ''.join(fp.readlines())
2771 elif content_type == 'text/html':
2772 return get_html_page(url)
2773 # Errors outside the url handler are caught by the server.
2774 raise TypeError('unknown content type %r for url %s' % (content_type, url))
2775
2776
2777 def browse(port=0, *, open_browser=True, hostname='localhost'):
2778 """Start the enhanced pydoc web server and open a web browser.
2779
2780 Use port '0' to start the server on an arbitrary port.
2781 Set open_browser to False to suppress opening a browser.
2782 """
2783 import webbrowser
2784 serverthread = _start_server(_url_handler, hostname, port)
2785 if serverthread.error:
2786 print(serverthread.error)
2787 return
2788 if serverthread.serving:
2789 server_help_msg = 'Server commands: [b]rowser, [q]uit'
2790 if open_browser:
2791 webbrowser.open(serverthread.url)
2792 try:
2793 print('Server ready at', serverthread.url)
2794 print(server_help_msg)
2795 while serverthread.serving:
2796 cmd = input('server> ')
2797 cmd = cmd.lower()
2798 if cmd == 'q':
2799 break
2800 elif cmd == 'b':
2801 webbrowser.open(serverthread.url)
2802 else:
2803 print(server_help_msg)
2804 except (KeyboardInterrupt, EOFError):
2805 print()
2806 finally:
2807 if serverthread.serving:
2808 serverthread.stop()
2809 print('Server stopped')
2810
2811
2812 # -------------------------------------------------- command-line interface
2813
2814 def ispath(x):
2815 return isinstance(x, str) and x.find(os.sep) >= 0
2816
2817 def _get_revised_path(given_path, argv0):
2818 """Ensures current directory is on returned path, and argv0 directory is not
2819
2820 Exception: argv0 dir is left alone if it's also pydoc's directory.
2821
2822 Returns a new path entry list, or None if no adjustment is needed.
2823 """
2824 # Scripts may get the current directory in their path by default if they're
2825 # run with the -m switch, or directly from the current directory.
2826 # The interactive prompt also allows imports from the current directory.
2827
2828 # Accordingly, if the current directory is already present, don't make
2829 # any changes to the given_path
2830 if '' in given_path or os.curdir in given_path or os.getcwd() in given_path:
2831 return None
2832
2833 # Otherwise, add the current directory to the given path, and remove the
2834 # script directory (as long as the latter isn't also pydoc's directory.
2835 stdlib_dir = os.path.dirname(__file__)
2836 script_dir = os.path.dirname(argv0)
2837 revised_path = given_path.copy()
2838 if script_dir in given_path and not os.path.samefile(script_dir, stdlib_dir):
2839 revised_path.remove(script_dir)
2840 revised_path.insert(0, os.getcwd())
2841 return revised_path
2842
2843
2844 # Note: the tests only cover _get_revised_path, not _adjust_cli_path itself
2845 def _adjust_cli_sys_path():
2846 """Ensures current directory is on sys.path, and __main__ directory is not.
2847
2848 Exception: __main__ dir is left alone if it's also pydoc's directory.
2849 """
2850 revised_path = _get_revised_path(sys.path, sys.argv[0])
2851 if revised_path is not None:
2852 sys.path[:] = revised_path
2853
2854
2855 def cli():
2856 """Command-line interface (looks at sys.argv to decide what to do)."""
2857 import getopt
2858 class BadUsage(Exception): pass
2859
2860 _adjust_cli_sys_path()
2861
2862 try:
2863 opts, args = getopt.getopt(sys.argv[1:], 'bk:n:p:w')
2864 writing = False
2865 start_server = False
2866 open_browser = False
2867 port = 0
2868 hostname = 'localhost'
2869 for opt, val in opts:
2870 if opt == '-b':
2871 start_server = True
2872 open_browser = True
2873 if opt == '-k':
2874 apropos(val)
2875 return
2876 if opt == '-p':
2877 start_server = True
2878 port = val
2879 if opt == '-w':
2880 writing = True
2881 if opt == '-n':
2882 start_server = True
2883 hostname = val
2884
2885 if start_server:
2886 browse(port, hostname=hostname, open_browser=open_browser)
2887 return
2888
2889 if not args: raise BadUsage
2890 for arg in args:
2891 if ispath(arg) and not os.path.exists(arg):
2892 print('file %r does not exist' % arg)
2893 sys.exit(1)
2894 try:
2895 if ispath(arg) and os.path.isfile(arg):
2896 arg = importfile(arg)
2897 if writing:
2898 if ispath(arg) and os.path.isdir(arg):
2899 writedocs(arg)
2900 else:
2901 writedoc(arg)
2902 else:
2903 help.help(arg, is_cli=True)
2904 except (ImportError, ErrorDuringImport) as value:
2905 print(value)
2906 sys.exit(1)
2907
2908 except (getopt.error, BadUsage):
2909 cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
2910 print("""pydoc - the Python documentation tool
2911
2912 {cmd} <name> ...
2913 Show text documentation on something. <name> may be the name of a
2914 Python keyword, topic, function, module, or package, or a dotted
2915 reference to a class or function within a module or module in a
2916 package. If <name> contains a '{sep}', it is used as the path to a
2917 Python source file to document. If name is 'keywords', 'topics',
2918 or 'modules', a listing of these things is displayed.
2919
2920 {cmd} -k <keyword>
2921 Search for a keyword in the synopsis lines of all available modules.
2922
2923 {cmd} -n <hostname>
2924 Start an HTTP server with the given hostname (default: localhost).
2925
2926 {cmd} -p <port>
2927 Start an HTTP server on the given port on the local machine. Port
2928 number 0 can be used to get an arbitrary unused port.
2929
2930 {cmd} -b
2931 Start an HTTP server on an arbitrary unused port and open a web browser
2932 to interactively browse documentation. This option can be used in
2933 combination with -n and/or -p.
2934
2935 {cmd} -w <name> ...
2936 Write out the HTML documentation for a module to a file in the current
2937 directory. If <name> contains a '{sep}', it is treated as a filename; if
2938 it names a directory, documentation is written for all the contents.
2939 """.format(cmd=cmd, sep=os.sep))
2940
2941 if __name__ == '__main__':
2942 cli()