Skip to content

Commit 37e5afe

Browse files
authored
BUG: use last __init__ to document class variables (#249)
* BUG: use last __init__ to document class variables * BUG: add unit test for multiple __init__ * BUG: amend multiple __init__ test Co-authored-by: Nicholas Coltharp <[email protected]>
1 parent 6cfbc4f commit 37e5afe

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

pdoc/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,8 @@ def _pep224_docstrings(doc_obj: Union['Module', 'Class'], *,
262262
tree = tree.body[0] # ast.parse creates a dummy ast.Module wrapper
263263

264264
# For classes, maybe add instance variables defined in __init__
265-
for node in tree.body:
265+
# Get the *last* __init__ node in case it is preceded by @overloads.
266+
for node in reversed(tree.body):
266267
if isinstance(node, ast.FunctionDef) and node.name == '__init__':
267268
instance_vars, _ = _pep224_docstrings(doc_obj, _init_tree=node)
268269
break

pdoc/test/__init__.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -889,22 +889,29 @@ def test_Variable_type_annotation_py36plus(self):
889889
filename = os.path.join(path, 'module36syntax.py')
890890
with open(filename, 'w') as f:
891891
f.write('''
892+
from typing import overload
893+
892894
var: str = 'x'
893895
"""dummy"""
894896
895897
class Foo:
896898
var: int = 3
897899
"""dummy"""
898900
899-
def __init__(self):
900-
self.var2: float = 1
901-
"""dummy"""
901+
@overload
902+
def __init__(self, var2: float):
903+
pass
904+
905+
def __init__(self, var2):
906+
self.var2: float = float(var2)
907+
"""dummy2"""
902908
''')
903909
mod = pdoc.Module(pdoc.import_module(filename))
904910
self.assertEqual(mod.doc['var'].type_annotation(), 'str')
905911
self.assertEqual(mod.doc['Foo'].doc['var'].type_annotation(), 'int')
906912
self.assertIsInstance(mod.doc['Foo'].doc['var2'], pdoc.Variable)
907913
self.assertEqual(mod.doc['Foo'].doc['var2'].type_annotation(), '') # Won't fix
914+
self.assertEqual(mod.doc['Foo'].doc['var2'].docstring, 'dummy2')
908915

909916
self.assertIn('var: str', mod.text())
910917
self.assertIn('var: int', mod.text())

0 commit comments

Comments
 (0)