-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
__init__.py
1539 lines (1291 loc) · 56.1 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Python package `pdoc` provides types, functions, and a command-line
interface for accessing public documentation of Python modules, and
for presenting it in a user-friendly, industry-standard open format.
It is best suited for small- to medium-sized projects with tidy,
hierarchical APIs.
.. include:: ./documentation.md
"""
import ast
import enum
import importlib.machinery
import importlib.util
import inspect
import os
import os.path as path
import re
import sys
import typing
from contextlib import contextmanager
from copy import copy
from functools import lru_cache, reduce, partial
from itertools import tee, groupby
from types import ModuleType
from typing import (
cast, Any, Callable, Dict, Generator, Iterable, List, Mapping, Optional, Set, Tuple,
Type, TypeVar, Union,
)
from warnings import warn
from mako.lookup import TemplateLookup
from mako.exceptions import TopLevelLookupException
from mako.template import Template
try:
from pdoc._version import version as __version__ # noqa: F401
except ImportError:
__version__ = '???' # Package not installed
_get_type_hints = lru_cache()(typing.get_type_hints)
_URL_MODULE_SUFFIX = '.html'
_URL_INDEX_MODULE_SUFFIX = '.m.html' # For modules named literal 'index'
_URL_PACKAGE_SUFFIX = '/index.html'
# type.__module__ can be None by the Python spec. In those cases, use this value
_UNKNOWN_MODULE = '?'
T = TypeVar('T', 'Module', 'Class', 'Function', 'Variable')
__pdoc__ = {} # type: Dict[str, Union[bool, str]]
tpl_lookup = TemplateLookup(
cache_args=dict(cached=True,
cache_type='memory'),
input_encoding='utf-8',
directories=[path.join(path.dirname(__file__), "templates")],
)
"""
A `mako.lookup.TemplateLookup` object that knows how to load templates
from the file system. You may add additional paths by modifying the
object's `directories` attribute.
"""
if os.getenv("XDG_CONFIG_HOME"):
tpl_lookup.directories.insert(0, path.join(os.getenv("XDG_CONFIG_HOME", ''), "pdoc"))
class Context(dict):
"""
The context object that maps all documented identifiers
(`pdoc.Doc.refname`) to their respective `pdoc.Doc` objects.
You can pass an instance of `pdoc.Context` to `pdoc.Module` constructor.
All `pdoc.Module` objects that share the same `pdoc.Context` will see
(and be able to link in HTML to) each other's identifiers.
If you don't pass your own `Context` instance to `Module` constructor,
a global context object will be used.
"""
__pdoc__['Context.__init__'] = False
_global_context = Context()
def reset():
"""Resets the global `pdoc.Context` to the initial (empty) state."""
global _global_context
_global_context.clear()
# Clear LRU caches
for func in (_get_type_hints,):
func.cache_clear()
for cls in (Doc, Module, Class, Function, Variable, External):
for _, method in inspect.getmembers(cls):
if isinstance(method, property):
method = method.fget
if hasattr(method, 'cache_clear'):
method.cache_clear()
def _get_config(**kwargs):
# Apply config.mako configuration
MAKO_INTERNALS = Template('').module.__dict__.keys()
DEFAULT_CONFIG = path.join(path.dirname(__file__), 'templates', 'config.mako')
config = {}
for config_module in (Template(filename=DEFAULT_CONFIG).module,
tpl_lookup.get_template('/config.mako').module):
config.update((var, getattr(config_module, var, None))
for var in config_module.__dict__
if var not in MAKO_INTERNALS)
known_keys = (set(config)
| {'docformat'} # Feature. https://github.com/pdoc3/pdoc/issues/169
# deprecated
| {'module', 'modules', 'http_server', 'external_links', 'search_query'})
invalid_keys = {k: v for k, v in kwargs.items() if k not in known_keys}
if invalid_keys:
warn('Unknown configuration variables (not in config.mako): {}'.format(invalid_keys))
config.update(kwargs)
if 'search_query' in config:
warn('Option `search_query` has been depricated, use `google_search_query` instead',
DeprecationWarning, stacklevel=2)
config['google_search_query'] = config['search_query']
del config['search_query']
return config
def _render_template(template_name, **kwargs):
"""
Returns the Mako template with the given name. If the template
cannot be found, a nicer error message is displayed.
"""
config = _get_config(**kwargs)
try:
t = tpl_lookup.get_template(template_name)
except TopLevelLookupException:
raise OSError(
"No template found at any of: {}".format(
', '.join(path.join(p, template_name.lstrip("/"))
for p in tpl_lookup.directories)))
try:
return t.render(**config).strip()
except Exception:
from mako import exceptions
print(exceptions.text_error_template().render(),
file=sys.stderr)
raise
def html(module_name, docfilter=None, reload=False, skip_errors=False, **kwargs) -> str:
"""
Returns the documentation for the module `module_name` in HTML
format. The module must be a module or an importable string.
`docfilter` is an optional predicate that controls which
documentation objects are shown in the output. It is a function
that takes a single argument (a documentation object) and returns
`True` or `False`. If `False`, that object will not be documented.
"""
mod = Module(import_module(module_name, reload=reload),
docfilter=docfilter, skip_errors=skip_errors)
link_inheritance()
return mod.html(**kwargs)
def text(module_name, docfilter=None, reload=False, skip_errors=False, **kwargs) -> str:
"""
Returns the documentation for the module `module_name` in plain
text format suitable for viewing on a terminal.
The module must be a module or an importable string.
`docfilter` is an optional predicate that controls which
documentation objects are shown in the output. It is a function
that takes a single argument (a documentation object) and returns
`True` or `False`. If `False`, that object will not be documented.
"""
mod = Module(import_module(module_name, reload=reload),
docfilter=docfilter, skip_errors=skip_errors)
link_inheritance()
return mod.text(**kwargs)
def import_module(module: Union[str, ModuleType],
*, reload: bool = False) -> ModuleType:
"""
Return module object matching `module` specification (either a python
module path or a filesystem path to file/directory).
"""
@contextmanager
def _module_path(module):
from os.path import abspath, dirname, isfile, isdir, split
path = '_pdoc_dummy_nonexistent'
module_name = inspect.getmodulename(module)
if isdir(module):
path, module = split(abspath(module))
elif isfile(module) and module_name:
path, module = dirname(abspath(module)), module_name
try:
sys.path.insert(0, path)
yield module
finally:
sys.path.remove(path)
if isinstance(module, Module):
module = module.obj
if isinstance(module, str):
with _module_path(module) as module_path:
try:
module = importlib.import_module(module_path)
except Exception as e:
raise ImportError('Error importing {!r}: {}: {}'
.format(module, e.__class__.__name__, e))
assert inspect.ismodule(module)
# If this is pdoc itself, return without reloading. Otherwise later
# `isinstance(..., pdoc.Doc)` calls won't work correctly.
if reload and not module.__name__.startswith(__name__):
module = importlib.reload(module)
return module
def _pairwise(iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ..."""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def _pep224_docstrings(doc_obj: Union['Module', 'Class'], *,
_init_tree=None) -> Tuple[Dict[str, str],
Dict[str, str]]:
"""
Extracts PEP-224 docstrings for variables of `doc_obj`
(either a `pdoc.Module` or `pdoc.Class`).
Returns a tuple of two dicts mapping variable names to their docstrings.
The second dict contains instance variables and is non-empty only in case
`doc_obj` is a `pdoc.Class` which has `__init__` method.
"""
# No variables in namespace packages
if isinstance(doc_obj, Module) and doc_obj.is_namespace:
return {}, {}
vars = {} # type: Dict[str, str]
instance_vars = {} # type: Dict[str, str]
if _init_tree:
tree = _init_tree
else:
try:
# Maybe raise exceptions with appropriate message
# before using cleaned doc_obj.source
_ = inspect.findsource(doc_obj.obj)
tree = ast.parse(doc_obj.source) # type: ignore
except (OSError, TypeError, SyntaxError) as exc:
warn("Couldn't read PEP-224 variable docstrings from {!r}: {}".format(doc_obj, exc))
return {}, {}
if isinstance(doc_obj, Class):
tree = tree.body[0] # ast.parse creates a dummy ast.Module wrapper
# For classes, maybe add instance variables defined in __init__
# Get the *last* __init__ node in case it is preceded by @overloads.
for node in reversed(tree.body):
if isinstance(node, ast.FunctionDef) and node.name == '__init__':
instance_vars, _ = _pep224_docstrings(doc_obj, _init_tree=node)
break
try:
ast_AnnAssign = ast.AnnAssign # type: Type
except AttributeError: # Python < 3.6
ast_AnnAssign = type(None)
ast_Assignments = (ast.Assign, ast_AnnAssign)
for assign_node, str_node in _pairwise(ast.iter_child_nodes(tree)):
if not (isinstance(assign_node, ast_Assignments) and
isinstance(str_node, ast.Expr) and
isinstance(str_node.value, ast.Str)):
continue
if isinstance(assign_node, ast.Assign) and len(assign_node.targets) == 1:
target = assign_node.targets[0]
elif isinstance(assign_node, ast_AnnAssign):
target = assign_node.target
# Skip the annotation. PEP 526 says:
# > Putting the instance variable annotations together in the class
# > makes it easier to find them, and helps a first-time reader of the code.
else:
continue
if not _init_tree and isinstance(target, ast.Name):
name = target.id
elif (_init_tree and
isinstance(target, ast.Attribute) and
isinstance(target.value, ast.Name) and
target.value.id == 'self'):
name = target.attr
else:
continue
if not _is_public(name) and not _is_whitelisted(name, doc_obj):
continue
docstring = inspect.cleandoc(str_node.value.s).strip()
if not docstring:
continue
vars[name] = docstring
return vars, instance_vars
def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']):
"""
Returns `True` if `name` (relative or absolute refname) is
contained in some module's __pdoc__ with a truish value.
"""
refname = doc_obj.refname + '.' + name
module = doc_obj.module
while module:
qualname = refname[len(module.refname) + 1:]
if module.__pdoc__.get(qualname) or module.__pdoc__.get(refname):
return True
module = module.supermodule
return False
def _is_blacklisted(name: str, doc_obj: Union['Module', 'Class']):
"""
Returns `True` if `name` (relative or absolute refname) is
contained in some module's __pdoc__ with value False.
"""
refname = doc_obj.refname + '.' + name
module = doc_obj.module
while module:
qualname = refname[len(module.refname) + 1:]
if module.__pdoc__.get(qualname) is False or module.__pdoc__.get(refname) is False:
return True
module = module.supermodule
return False
def _is_public(ident_name):
"""
Returns `True` if `ident_name` matches the export criteria for an
identifier name.
"""
return not ident_name.startswith("_")
def _is_function(obj):
return inspect.isroutine(obj) and callable(obj)
def _is_descriptor(obj):
return (inspect.isdatadescriptor(obj) or
inspect.ismethoddescriptor(obj) or
inspect.isgetsetdescriptor(obj) or
inspect.ismemberdescriptor(obj))
def _filter_type(type: Type[T],
values: Union[Iterable['Doc'], Mapping[str, 'Doc']]) -> List[T]:
"""
Return a list of values from `values` of type `type`.
"""
if isinstance(values, dict):
values = values.values()
return [i for i in values if isinstance(i, type)]
def _toposort(graph: Mapping[T, Set[T]]) -> Generator[T, None, None]:
"""
Return items of `graph` sorted in topological order.
Source: https://rosettacode.org/wiki/Topological_sort#Python
"""
items_without_deps = reduce(set.union, graph.values(), set()) - set(graph.keys()) # type: ignore # noqa: E501
yield from items_without_deps
ordered = items_without_deps
while True:
graph = {item: (deps - ordered)
for item, deps in graph.items()
if item not in ordered}
ordered = {item
for item, deps in graph.items()
if not deps}
yield from ordered
if not ordered:
break
assert not graph, "A cyclic dependency exists amongst %r" % graph
def link_inheritance(context: Context = None):
"""
Link inheritance relationsships between `pdoc.Class` objects
(and between their members) of all `pdoc.Module` objects that
share the provided `context` (`pdoc.Context`).
You need to call this if you expect `pdoc.Doc.inherits` and
inherited `pdoc.Doc.docstring` to be set correctly.
"""
if context is None:
context = _global_context
graph = {cls: set(cls.mro(only_documented=True))
for cls in _filter_type(Class, context)}
for cls in _toposort(graph):
cls._fill_inheritance()
for module in _filter_type(Module, context):
module._link_inheritance()
class Doc:
"""
A base class for all documentation objects.
A documentation object corresponds to *something* in a Python module
that has a docstring associated with it. Typically, this includes
modules, classes, functions, and methods. However, `pdoc` adds support
for extracting some docstrings from abstract syntax trees, making
(module, class or instance) variables supported too.
A special type of documentation object `pdoc.External` is used to
represent identifiers that are not part of the public interface of
a module. (The name "External" is a bit of a misnomer, since it can
also correspond to unexported members of the module, particularly in
a class's ancestor list.)
"""
__slots__ = ('module', 'name', 'obj', 'docstring', 'inherits')
def __init__(self, name, module, obj, docstring=None):
"""
Initializes a documentation object, where `name` is the public
identifier name, `module` is a `pdoc.Module` object where raw
Python object `obj` is defined, and `docstring` is its
documentation string. If `docstring` is left empty, it will be
read with `inspect.getdoc()`.
"""
self.module = module
"""
The module documentation object that this object is defined in.
"""
self.name = name
"""
The identifier name for this object.
"""
self.obj = obj
"""
The raw python object.
"""
docstring = (docstring or inspect.getdoc(obj) or '').strip()
if '.. include::' in docstring:
from pdoc.html_helpers import _ToMarkdown
docstring = _ToMarkdown.admonitions(docstring, self.module, ('include',))
self.docstring = docstring
"""
The cleaned docstring for this object with any `.. include::`
directives resolved (i.e. content included).
"""
self.inherits = None # type: Optional[Union[Class, Function, Variable]]
"""
The Doc object (Class, Function, or Variable) this object inherits from,
if any.
"""
def __repr__(self):
return '<{} {!r}>'.format(self.__class__.__name__, self.refname)
@property # type: ignore
@lru_cache()
def source(self) -> str:
"""
Cleaned (dedented) source code of the Python object. If not
available, an empty string.
"""
try:
lines, _ = inspect.getsourcelines(self.obj)
except (ValueError, TypeError, OSError):
return ''
return inspect.cleandoc(''.join(['\n'] + lines))
@property
def refname(self) -> str:
"""
Reference name of this documentation
object, usually its fully qualified path
(e.g. <code>pdoc.Doc.refname</code>). Every
documentation object provides this property.
"""
# Ok for Module and External, the rest need it overriden
return self.name
@property
def qualname(self) -> str:
"""
Module-relative "qualified" name of this documentation
object, used for show (e.g. <code>Doc.qualname</code>).
"""
return getattr(self.obj, '__qualname__', self.name)
@lru_cache()
def url(self, relative_to: 'Module' = None, *, link_prefix: str = '',
top_ancestor: bool = False) -> str:
"""
Canonical relative URL (including page fragment) for this
documentation object.
Specify `relative_to` (a `pdoc.Module` object) to obtain a
relative URL.
For usage of `link_prefix` see `pdoc.html()`.
If `top_ancestor` is `True`, the returned URL instead points to
the top ancestor in the object's `pdoc.Doc.inherits` chain.
"""
if top_ancestor:
self = self._inherits_top()
if relative_to is None or link_prefix:
return link_prefix + self._url()
if self.module.name == relative_to.name:
return '#' + self.refname
# Otherwise, compute relative path from current module to link target
url = os.path.relpath(self._url(), relative_to.url()).replace(path.sep, '/')
# We have one set of '..' too many
if url.startswith('../'):
url = url[3:]
return url
def _url(self):
return self.module._url() + '#' + self.refname
def _inherits_top(self):
"""
Follow the `pdoc.Doc.inherits` chain and return the top object.
"""
top = self
while top.inherits:
top = top.inherits
return top
def __lt__(self, other):
return self.refname < other.refname
class Module(Doc):
"""
Representation of a module's documentation.
"""
__pdoc__["Module.name"] = """
The name of this module with respect to the context/path in which
it was imported from. It is always an absolute import path.
"""
__slots__ = ('supermodule', 'doc', '_context', '_is_inheritance_linked',
'_skipped_submodules')
def __init__(self, module: Union[ModuleType, str], *, docfilter: Callable[[Doc], bool] = None,
supermodule: 'Module' = None, context: Context = None,
skip_errors: bool = False):
"""
Creates a `Module` documentation object given the actual
module Python object.
`docfilter` is an optional predicate that controls which
sub-objects are documentated (see also: `pdoc.html()`).
`supermodule` is the parent `pdoc.Module` this module is
a submodule of.
`context` is an instance of `pdoc.Context`. If `None` a
global context object will be used.
If `skip_errors` is `True` and an unimportable, erroneous
submodule is encountered, a warning will be issued instead
of raising an exception.
"""
if isinstance(module, str):
module = import_module(module)
super().__init__(module.__name__, self, module)
if self.name.endswith('.__init__') and not self.is_package:
self.name = self.name[:-len('.__init__')]
self._context = _global_context if context is None else context
"""
A lookup table for ALL doc objects of all modules that share this context,
mainly used in `Module.find_ident()`.
"""
self.supermodule = supermodule
"""
The parent `pdoc.Module` this module is a submodule of, or `None`.
"""
self.doc = {} # type: Dict[str, Union[Module, Class, Function, Variable]]
"""A mapping from identifier name to a documentation object."""
self._is_inheritance_linked = False
"""Re-entry guard for `pdoc.Module._link_inheritance()`."""
self._skipped_submodules = set()
var_docstrings, _ = _pep224_docstrings(self)
# Populate self.doc with this module's public members
if hasattr(self.obj, '__all__'):
public_objs = []
for name in self.obj.__all__:
try:
public_objs.append((name, getattr(self.obj, name)))
except AttributeError:
warn("Module {!r} doesn't contain identifier `{}` "
"exported in `__all__`".format(self.module, name))
else:
def is_from_this_module(obj):
mod = inspect.getmodule(inspect.unwrap(obj))
return mod is None or mod.__name__ == self.obj.__name__
public_objs = [(name, inspect.unwrap(obj))
for name, obj in inspect.getmembers(self.obj)
if ((_is_public(name) or _is_whitelisted(name, self)) and
(is_from_this_module(obj) or name in var_docstrings))]
index = list(self.obj.__dict__).index
public_objs.sort(key=lambda i: index(i[0]))
for name, obj in public_objs:
if _is_function(obj):
self.doc[name] = Function(name, self, obj)
elif inspect.isclass(obj):
self.doc[name] = Class(name, self, obj)
elif name in var_docstrings:
self.doc[name] = Variable(name, self, var_docstrings[name], obj=obj)
# If the module is a package, scan the directory for submodules
if self.is_package:
def iter_modules(paths):
"""
Custom implementation of `pkgutil.iter_modules()`
because that one doesn't play well with namespace packages.
See: https://github.com/pypa/setuptools/issues/83
"""
from os.path import isdir, join
for pth in paths:
for file in os.listdir(pth):
if file.startswith(('.', '__pycache__', '__init__.py')):
continue
module_name = inspect.getmodulename(file)
if module_name:
yield module_name
if isdir(join(pth, file)) and '.' not in file:
yield file
for root in iter_modules(self.obj.__path__):
# Ignore if this module was already doc'd.
if root in self.doc:
continue
# Ignore if it isn't exported
if not _is_public(root) and not _is_whitelisted(root, self):
continue
if _is_blacklisted(root, self):
self._skipped_submodules.add(root)
continue
assert self.refname == self.name
fullname = "%s.%s" % (self.name, root)
try:
m = Module(import_module(fullname),
docfilter=docfilter, supermodule=self,
context=self._context, skip_errors=skip_errors)
except Exception as ex:
if skip_errors:
warn(str(ex), Module.ImportWarning)
continue
raise
self.doc[root] = m
# Skip empty namespace packages because they may
# as well be other auxiliary directories
if m.is_namespace and not m.doc:
del self.doc[root]
self._context.pop(m.refname)
# Apply docfilter
if docfilter:
for name, dobj in self.doc.copy().items():
if not docfilter(dobj):
self.doc.pop(name)
self._context.pop(dobj.refname, None)
# Build the reference name dictionary of the module
self._context[self.refname] = self
for docobj in self.doc.values():
self._context[docobj.refname] = docobj
if isinstance(docobj, Class):
self._context.update((obj.refname, obj)
for obj in docobj.doc.values())
class ImportWarning(UserWarning):
"""
Our custom import warning because the builtin is ignored by default.
https://docs.python.org/3/library/warnings.html#default-warning-filter
"""
__pdoc__['Module.ImportWarning'] = False
@property
def __pdoc__(self):
"""This module's __pdoc__ dict, or an empty dict if none."""
return getattr(self.obj, '__pdoc__', {})
def _link_inheritance(self):
# Inherited members are already in place since
# `Class._fill_inheritance()` has been called from
# `pdoc.fill_inheritance()`.
# Now look for docstrings in the module's __pdoc__ override.
if self._is_inheritance_linked:
# Prevent re-linking inheritance for modules which have already
# had done so. Otherwise, this would raise "does not exist"
# errors if `pdoc.link_inheritance()` is called multiple times.
return
# Apply __pdoc__ overrides
for name, docstring in self.__pdoc__.items():
# In case of whitelisting with "True", there's nothing to do
if docstring is True:
continue
refname = "%s.%s" % (self.refname, name)
if docstring in (False, None):
if docstring is None:
warn('Setting `__pdoc__[key] = None` is deprecated; '
'use `__pdoc__[key] = False` '
'(key: {!r}, module: {!r}).'.format(name, self.name))
if name in self._skipped_submodules:
continue
if (not name.endswith('.__init__') and
name not in self.doc and refname not in self._context):
warn('__pdoc__-overriden key {!r} does not exist '
'in module {!r}'.format(name, self.name))
obj = self.find_ident(name)
cls = getattr(obj, 'cls', None)
if cls:
del cls.doc[obj.name]
self.doc.pop(name, None)
self._context.pop(refname, None)
# Pop also all that startwith refname
for key in list(self._context.keys()):
if key.startswith(refname + '.'):
del self._context[key]
continue
dobj = self.find_ident(refname)
if isinstance(dobj, External):
continue
if not isinstance(docstring, str):
raise ValueError('__pdoc__ dict values must be strings;'
'__pdoc__[{!r}] is of type {}'.format(name, type(docstring)))
dobj.docstring = inspect.cleandoc(docstring)
# Now after docstrings are set correctly, continue the
# inheritance routine, marking members inherited or not
for c in _filter_type(Class, self.doc):
c._link_inheritance()
self._is_inheritance_linked = True
def text(self, **kwargs) -> str:
"""
Returns the documentation for this module as plain text.
"""
txt = _render_template('/text.mako', module=self, **kwargs)
return re.sub("\n\n\n+", "\n\n", txt)
def html(self, minify=True, **kwargs) -> str:
"""
Returns the documentation for this module as
self-contained HTML.
If `minify` is `True`, the resulting HTML is minified.
For explanation of other arguments, see `pdoc.html()`.
`kwargs` is passed to the `mako` render function.
"""
html = _render_template('/html.mako', module=self, **kwargs)
if minify:
from pdoc.html_helpers import minify_html
html = minify_html(html)
return html
@property
def is_package(self) -> bool:
"""
`True` if this module is a package.
Works by checking whether the module has a `__path__` attribute.
"""
return hasattr(self.obj, "__path__")
@property
def is_namespace(self) -> bool:
"""
`True` if this module is a namespace package.
"""
try:
return self.obj.__spec__.origin in (None, 'namespace') # None in Py3.7+
except AttributeError:
return False
def find_class(self, cls: type) -> Doc:
"""
Given a Python `cls` object, try to find it in this module
or in any of the exported identifiers of the submodules.
"""
# XXX: Is this corrent? Does it always match
# `Class.module.name + Class.qualname`?. Especially now?
# If not, see what was here before.
return self.find_ident((cls.__module__ or _UNKNOWN_MODULE) + '.' + cls.__qualname__)
def find_ident(self, name: str) -> Doc:
"""
Searches this module and **all** other public modules
for an identifier with name `name` in its list of
exported identifiers.
The documentation object corresponding to the identifier is
returned. If one cannot be found, then an instance of
`External` is returned populated with the given identifier.
"""
_name = name.rstrip('()') # Function specified with parentheses
if _name.endswith('.__init__'): # Ref to class' init is ref to class itself
_name = _name[:-len('.__init__')]
return (self.doc.get(_name) or
self._context.get(_name) or
self._context.get(self.name + '.' + _name) or
External(name))
def _filter_doc_objs(self, type: Type[T], sort=True) -> List[T]:
result = _filter_type(type, self.doc)
return sorted(result) if sort else result
def variables(self, sort=True) -> List['Variable']:
"""
Returns all documented module-level variables in the module,
optionally sorted alphabetically, as a list of `pdoc.Variable`.
"""
return self._filter_doc_objs(Variable, sort)
def classes(self, sort=True) -> List['Class']:
"""
Returns all documented module-level classes in the module,
optionally sorted alphabetically, as a list of `pdoc.Class`.
"""
return self._filter_doc_objs(Class, sort)
def functions(self, sort=True) -> List['Function']:
"""
Returns all documented module-level functions in the module,
optionally sorted alphabetically, as a list of `pdoc.Function`.
"""
return self._filter_doc_objs(Function, sort)
def submodules(self) -> List['Module']:
"""
Returns all documented sub-modules of the module sorted
alphabetically as a list of `pdoc.Module`.
"""
return self._filter_doc_objs(Module)
def _url(self):
url = self.module.name.replace('.', '/')
if self.is_package:
return url + _URL_PACKAGE_SUFFIX
elif url.endswith('/index'):
return url + _URL_INDEX_MODULE_SUFFIX
return url + _URL_MODULE_SUFFIX
def _getmembers_all(obj: type) -> List[Tuple[str, Any]]:
# The following code based on inspect.getmembers() @ 5b23f7618d43
mro = obj.__mro__[:-1] # Skip object
names = set(dir(obj))
# Add keys from bases
for base in mro:
names.update(base.__dict__.keys())
# Add members for which type annotations exist
names.update(getattr(obj, '__annotations__', {}).keys())
results = []
for name in names:
try:
value = getattr(obj, name)
except AttributeError:
for base in mro:
if name in base.__dict__:
value = base.__dict__[name]
break
else:
# Missing slot member or a buggy __dir__;
# In out case likely a type-annotated member
# which we'll interpret as a variable
value = None
results.append((name, value))
return results
class Class(Doc):
"""
Representation of a class' documentation.
"""
__slots__ = ('doc', '_super_members')
def __init__(self, name, module, obj, *, docstring=None):
assert inspect.isclass(obj)
if docstring is None:
init_doc = inspect.getdoc(obj.__init__) or ''
if init_doc == object.__init__.__doc__:
init_doc = ''
docstring = ((inspect.getdoc(obj) or '') + '\n\n' + init_doc).strip()
super().__init__(name, module, obj, docstring=docstring)
self.doc = {} # type: Dict[str, Union[Function, Variable]]
"""A mapping from identifier name to a `pdoc.Doc` objects."""
# Annotations for filtering.
# Use only own, non-inherited annotations (the rest will be inherited)
annotations = getattr(self.obj, '__annotations__', {})
public_objs = [(_name, inspect.unwrap(obj))
for _name, obj in _getmembers_all(self.obj)
# Filter only *own* members. The rest are inherited
# in Class._fill_inheritance()
if (_name in self.obj.__dict__ or _name in annotations)
and (_is_public(_name) or _is_whitelisted(_name, self))]
def definition_order_index(
name,
_annot_index=list(annotations).index,
_dict_index=list(self.obj.__dict__).index):
try:
return _dict_index(name)
except ValueError:
pass
try:
return _annot_index(name) - len(annotations) # sort annotated first
except ValueError:
return 9e9
public_objs.sort(key=lambda i: definition_order_index(i[0]))
var_docstrings, instance_var_docstrings = _pep224_docstrings(self)
# Convert the public Python objects to documentation objects.
for name, obj in public_objs:
if _is_function(obj):
self.doc[name] = Function(
name, self.module, obj, cls=self)
else:
self.doc[name] = Variable(
name, self.module,
docstring=(
var_docstrings.get(name) or
(inspect.isclass(obj) or _is_descriptor(obj)) and inspect.getdoc(obj)),
cls=self,
obj=getattr(obj, 'fget', getattr(obj, '__get__', None)),
instance_var=(_is_descriptor(obj) or
name in getattr(self.obj, '__slots__', ())))
for name, docstring in instance_var_docstrings.items():
self.doc[name] = Variable(
name, self.module, docstring, cls=self,
obj=getattr(self.obj, name, None),
instance_var=True)