Debian Codegraph @

lib-python/3/pydoc.py

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