Skip to content

Commit dae8a00

Browse files
committed
REF: Add/convert some easy typing annotations
1 parent 28b366a commit dae8a00

File tree

2 files changed

+20
-29
lines changed

2 files changed

+20
-29
lines changed

pdoc/__init__.py

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949

5050
T = TypeVar('T', 'Module', 'Class', 'Function', 'Variable')
5151

52-
__pdoc__ = {} # type: Dict[str, Union[bool, str]]
52+
__pdoc__: Dict[str, Union[bool, str]] = {}
5353

5454
tpl_lookup = TemplateLookup(
5555
cache_args=dict(cached=True,
@@ -255,8 +255,8 @@ def _pep224_docstrings(doc_obj: Union['Module', 'Class'], *,
255255
if isinstance(doc_obj, Module) and doc_obj.is_namespace:
256256
return {}, {}
257257

258-
vars = {} # type: Dict[str, str]
259-
instance_vars = {} # type: Dict[str, str]
258+
vars: Dict[str, str] = {}
259+
instance_vars: Dict[str, str] = {}
260260

261261
if _init_tree:
262262
tree = _init_tree
@@ -284,21 +284,15 @@ def _pep224_docstrings(doc_obj: Union['Module', 'Class'], *,
284284
instance_vars, _ = _pep224_docstrings(doc_obj, _init_tree=node)
285285
break
286286

287-
try:
288-
ast_AnnAssign = ast.AnnAssign # type: Type
289-
except AttributeError: # Python < 3.6
290-
ast_AnnAssign = type(None)
291-
ast_Assignments = (ast.Assign, ast_AnnAssign)
292-
293287
for assign_node, str_node in _pairwise(ast.iter_child_nodes(tree)):
294-
if not (isinstance(assign_node, ast_Assignments) and
288+
if not (isinstance(assign_node, (ast.Assign, ast.AnnAssign)) and
295289
isinstance(str_node, ast.Expr) and
296290
isinstance(str_node.value, ast.Str)):
297291
continue
298292

299293
if isinstance(assign_node, ast.Assign) and len(assign_node.targets) == 1:
300294
target = assign_node.targets[0]
301-
elif isinstance(assign_node, ast_AnnAssign):
295+
elif isinstance(assign_node, ast.AnnAssign):
302296
target = assign_node.target
303297
# Skip the annotation. PEP 526 says:
304298
# > Putting the instance variable annotations together in the class
@@ -335,7 +329,7 @@ def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']):
335329
contained in some module's __pdoc__ with a truish value.
336330
"""
337331
refname = doc_obj.refname + '.' + name
338-
module = doc_obj.module
332+
module: Optional[Module] = doc_obj.module
339333
while module:
340334
qualname = refname[len(module.refname) + 1:]
341335
if module.__pdoc__.get(qualname) or module.__pdoc__.get(refname):
@@ -351,7 +345,7 @@ def _is_blacklisted(name: str, doc_obj: Union['Module', 'Class']):
351345
contained in some module's __pdoc__ with value False.
352346
"""
353347
refname = doc_obj.refname + '.' + name
354-
module = doc_obj.module
348+
module: Optional[Module] = doc_obj.module
355349
while module:
356350
qualname = refname[len(module.refname) + 1:]
357351
if module.__pdoc__.get(qualname) is False or module.__pdoc__.get(refname) is False:
@@ -450,7 +444,7 @@ class Doc:
450444
"""
451445
__slots__ = ('module', 'name', 'obj', 'docstring', 'inherits')
452446

453-
def __init__(self, name, module, obj, docstring=None):
447+
def __init__(self, name: str, module, obj, docstring: str = None):
454448
"""
455449
Initializes a documentation object, where `name` is the public
456450
identifier name, `module` is a `pdoc.Module` object where raw
@@ -483,7 +477,7 @@ def __init__(self, name, module, obj, docstring=None):
483477
directives resolved (i.e. content included).
484478
"""
485479

486-
self.inherits = None # type: Optional[Union[Class, Function, Variable]]
480+
self.inherits: Optional[Union[Class, Function, Variable]] = None
487481
"""
488482
The Doc object (Class, Function, or Variable) this object inherits from,
489483
if any.
@@ -621,7 +615,7 @@ def __init__(self, module: Union[ModuleType, str], *, docfilter: Callable[[Doc],
621615
The parent `pdoc.Module` this module is a submodule of, or `None`.
622616
"""
623617

624-
self.doc = {} # type: Dict[str, Union[Module, Class, Function, Variable]]
618+
self.doc: Dict[str, Union[Module, Class, Function, Variable]] = {}
625619
"""A mapping from identifier name to a documentation object."""
626620

627621
self._is_inheritance_linked = False
@@ -743,7 +737,7 @@ class ImportWarning(UserWarning):
743737
__pdoc__['Module.ImportWarning'] = False
744738

745739
@property
746-
def __pdoc__(self):
740+
def __pdoc__(self) -> dict:
747741
"""This module's __pdoc__ dict, or an empty dict if none."""
748742
return getattr(self.obj, '__pdoc__', {})
749743

@@ -957,7 +951,7 @@ class Class(Doc):
957951
"""
958952
__slots__ = ('doc', '_super_members')
959953

960-
def __init__(self, name, module, obj, *, docstring=None):
954+
def __init__(self, name: str, module: Module, obj, *, docstring: str = None):
961955
assert inspect.isclass(obj)
962956

963957
if docstring is None:
@@ -968,7 +962,7 @@ def __init__(self, name, module, obj, *, docstring=None):
968962

969963
super().__init__(name, module, obj, docstring=docstring)
970964

971-
self.doc = {} # type: Dict[str, Union[Function, Variable]]
965+
self.doc: Dict[str, Union[Function, Variable]] = {}
972966
"""A mapping from identifier name to a `pdoc.Doc` objects."""
973967

974968
# Annotations for filtering.
@@ -1056,7 +1050,7 @@ def mro(self, only_documented=False) -> List['Class']:
10561050
The list will contain objects of type `pdoc.Class`
10571051
if the types are documented, and `pdoc.External` otherwise.
10581052
"""
1059-
classes = [self.module.find_class(c)
1053+
classes = [cast(Class, self.module.find_class(c))
10601054
for c in inspect.getmro(self.obj)
10611055
if c not in (self.obj, object)]
10621056
if self in classes:
@@ -1079,7 +1073,7 @@ def subclasses(self) -> List['Class']:
10791073
The objects in the list are of type `pdoc.Class` if available,
10801074
and `pdoc.External` otherwise.
10811075
"""
1082-
return sorted(self.module.find_class(c)
1076+
return sorted(cast(Class, self.module.find_class(c))
10831077
for c in type.__subclasses__(self.obj))
10841078

10851079
def params(self, *, annotate=False, link=None) -> List[str]:
@@ -1221,7 +1215,7 @@ class Function(Doc):
12211215
"""
12221216
__slots__ = ('cls',)
12231217

1224-
def __init__(self, name, module, obj, *, cls: Class = None):
1218+
def __init__(self, name: str, module: Module, obj, *, cls: Class = None):
12251219
"""
12261220
Same as `pdoc.Doc`, except `obj` must be a
12271221
Python function object. The docstring is gathered automatically.
@@ -1492,8 +1486,8 @@ class Variable(Doc):
14921486
"""
14931487
__slots__ = ('cls', 'instance_var')
14941488

1495-
def __init__(self, name, module, docstring, *,
1496-
obj=None, cls: Class = None, instance_var=False):
1489+
def __init__(self, name: str, module: Module, docstring, *,
1490+
obj=None, cls: Class = None, instance_var: bool = False):
14971491
"""
14981492
Same as `pdoc.Doc`, except `cls` should be provided
14991493
as a `pdoc.Class` object when this is a class or instance
@@ -1552,7 +1546,7 @@ class External(Doc):
15521546
form.
15531547
"""
15541548

1555-
def __init__(self, name):
1549+
def __init__(self, name: str):
15561550
"""
15571551
Initializes an external identifier with `name`, where `name`
15581552
should be a fully qualified name.

pdoc/test/__init__.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -389,10 +389,7 @@ def test_pdf(self):
389389
err = stderr.getvalue()
390390
self.assertIn('pdoc3.github.io', out)
391391
self.assertIn('pandoc', err)
392-
393-
pdoc_Doc_params = str(inspect.signature(pdoc.Doc.__init__)).replace('self, ', '')
394-
self.assertIn(pdoc_Doc_params.replace(' ', ''),
395-
out.replace('>', '').replace('\n', '').replace(' ', ''))
392+
self.assertIn('Doc(name', out.replace('>', '').replace('\n', '').replace(' ', ''))
396393

397394
@unittest.skipUnless('PDOC_TEST_PANDOC' in os.environ, 'PDOC_TEST_PANDOC not set/requested')
398395
def test_pdf_pandoc(self):

0 commit comments

Comments
 (0)