Skip to content

Commit e207d72

Browse files
[3.9] bpo-40296: Fix supporting generic aliases in pydoc (GH-30253). (GH-31976) (GH-31981)
(cherry picked from commit cd44afc) (cherry picked from commit a5b7678)
1 parent cbcd2e3 commit e207d72

File tree

4 files changed

+83
-10
lines changed

4 files changed

+83
-10
lines changed

Lib/pydoc.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class or function within a module or module in a package. If the
6969
import sysconfig
7070
import time
7171
import tokenize
72+
import types
7273
import urllib.parse
7374
import warnings
7475
from collections import deque
@@ -90,21 +91,24 @@ def pathdirs():
9091
normdirs.append(normdir)
9192
return dirs
9293

94+
def _isclass(object):
95+
return inspect.isclass(object) and not isinstance(object, types.GenericAlias)
96+
9397
def _findclass(func):
9498
cls = sys.modules.get(func.__module__)
9599
if cls is None:
96100
return None
97101
for name in func.__qualname__.split('.')[:-1]:
98102
cls = getattr(cls, name)
99-
if not inspect.isclass(cls):
103+
if not _isclass(cls):
100104
return None
101105
return cls
102106

103107
def _finddoc(obj):
104108
if inspect.ismethod(obj):
105109
name = obj.__func__.__name__
106110
self = obj.__self__
107-
if (inspect.isclass(self) and
111+
if (_isclass(self) and
108112
getattr(getattr(self, name, None), '__func__') is obj.__func__):
109113
# classmethod
110114
cls = self
@@ -118,7 +122,7 @@ def _finddoc(obj):
118122
elif inspect.isbuiltin(obj):
119123
name = obj.__name__
120124
self = obj.__self__
121-
if (inspect.isclass(self) and
125+
if (_isclass(self) and
122126
self.__qualname__ + '.' + name == obj.__qualname__):
123127
# classmethod
124128
cls = self
@@ -205,7 +209,7 @@ def classname(object, modname):
205209

206210
def isdata(object):
207211
"""Check if an object is of a type that probably means it's data."""
208-
return not (inspect.ismodule(object) or inspect.isclass(object) or
212+
return not (inspect.ismodule(object) or _isclass(object) or
209213
inspect.isroutine(object) or inspect.isframe(object) or
210214
inspect.istraceback(object) or inspect.iscode(object))
211215

@@ -470,7 +474,7 @@ def document(self, object, name=None, *args):
470474
# by lacking a __name__ attribute) and an instance.
471475
try:
472476
if inspect.ismodule(object): return self.docmodule(*args)
473-
if inspect.isclass(object): return self.docclass(*args)
477+
if _isclass(object): return self.docclass(*args)
474478
if inspect.isroutine(object): return self.docroutine(*args)
475479
except AttributeError:
476480
pass
@@ -775,7 +779,7 @@ def docmodule(self, object, name=None, mod=None, *ignored):
775779
modules = inspect.getmembers(object, inspect.ismodule)
776780

777781
classes, cdict = [], {}
778-
for key, value in inspect.getmembers(object, inspect.isclass):
782+
for key, value in inspect.getmembers(object, _isclass):
779783
# if __all__ exists, believe it. Otherwise use old heuristic.
780784
if (all is not None or
781785
(inspect.getmodule(value) or object) is object):
@@ -1217,7 +1221,7 @@ def docmodule(self, object, name=None, mod=None):
12171221
result = result + self.section('DESCRIPTION', desc)
12181222

12191223
classes = []
1220-
for key, value in inspect.getmembers(object, inspect.isclass):
1224+
for key, value in inspect.getmembers(object, _isclass):
12211225
# if __all__ exists, believe it. Otherwise use old heuristic.
12221226
if (all is not None
12231227
or (inspect.getmodule(value) or object) is object):
@@ -1698,7 +1702,7 @@ def describe(thing):
16981702
return 'member descriptor %s.%s.%s' % (
16991703
thing.__objclass__.__module__, thing.__objclass__.__name__,
17001704
thing.__name__)
1701-
if inspect.isclass(thing):
1705+
if _isclass(thing):
17021706
return 'class ' + thing.__name__
17031707
if inspect.isfunction(thing):
17041708
return 'function ' + thing.__name__
@@ -1759,7 +1763,7 @@ def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
17591763
desc += ' in module ' + module.__name__
17601764

17611765
if not (inspect.ismodule(object) or
1762-
inspect.isclass(object) or
1766+
_isclass(object) or
17631767
inspect.isroutine(object) or
17641768
inspect.isdatadescriptor(object) or
17651769
_getdoc(object)):

Lib/test/pydoc_mod.py

+11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""This is a test module for test_pydoc"""
22

3+
import types
4+
import typing
5+
36
__author__ = "Benjamin Peterson"
47
__credits__ = "Nobody"
58
__version__ = "1.2.3.4"
@@ -24,6 +27,8 @@ def get_answer(self):
2427
def is_it_true(self):
2528
""" Return self.get_answer() """
2629
return self.get_answer()
30+
def __class_getitem__(self, item):
31+
return types.GenericAlias(self, item)
2732

2833
def doc_func():
2934
"""
@@ -35,3 +40,9 @@ def doc_func():
3540

3641
def nodoc_func():
3742
pass
43+
44+
45+
list_alias1 = typing.List[int]
46+
list_alias2 = list[int]
47+
c_alias = C[int]
48+
type_union1 = typing.Union[int, str]

Lib/test/test_pydoc.py

+58-1
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,11 @@ class C(builtins.object)
9595
| say_no(self)
9696
|\x20\x20
9797
| ----------------------------------------------------------------------
98+
| Class methods defined here:
99+
|\x20\x20
100+
| __class_getitem__(item) from builtins.type
101+
|\x20\x20
102+
| ----------------------------------------------------------------------
98103
| Data descriptors defined here:
99104
|\x20\x20
100105
| __dict__
@@ -114,6 +119,10 @@ class C(builtins.object)
114119
115120
DATA
116121
__xyz__ = 'X, Y and Z'
122+
c_alias = test.pydoc_mod.C[int]
123+
list_alias1 = typing.List[int]
124+
list_alias2 = list[int]
125+
type_union1 = typing.Union[int, str]
117126
118127
VERSION
119128
1.2.3.4
@@ -141,6 +150,15 @@ class C(builtins.object)
141150
<p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
142151
<p>
143152
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
153+
<tr bgcolor="#aa55cc">
154+
<td colspan=3 valign=bottom>&nbsp;<br>
155+
<font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
156+
\x20\x20\x20\x20
157+
<tr><td bgcolor="#aa55cc"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
158+
<td width="100%%"><table width="100%%" summary="list"><tr><td width="25%%" valign=top><a href="types.html">types</a><br>
159+
</td><td width="25%%" valign=top><a href="typing.html">typing</a><br>
160+
</td><td width="25%%" valign=top></td><td width="25%%" valign=top></td></tr></table></td></tr></table><p>
161+
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
144162
<tr bgcolor="#ee77aa">
145163
<td colspan=3 valign=bottom>&nbsp;<br>
146164
<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
@@ -210,6 +228,10 @@ class C(builtins.object)
210228
211229
<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
212230
231+
<hr>
232+
Class methods defined here:<br>
233+
<dl><dt><a name="C-__class_getitem__"><strong>__class_getitem__</strong></a>(item)<font color="#909090"><font face="helvetica, arial"> from <a href="builtins.html#type">builtins.type</a></font></font></dt></dl>
234+
213235
<hr>
214236
Data descriptors defined here:<br>
215237
<dl><dt><strong>__dict__</strong></dt>
@@ -237,7 +259,11 @@ class C(builtins.object)
237259
<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
238260
\x20\x20\x20\x20
239261
<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
240-
<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
262+
<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'<br>
263+
<strong>c_alias</strong> = test.pydoc_mod.C[int]<br>
264+
<strong>list_alias1</strong> = typing.List[int]<br>
265+
<strong>list_alias2</strong> = list[int]<br>
266+
<strong>type_union1</strong> = typing.Union[int, str]</td></tr></table><p>
241267
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
242268
<tr bgcolor="#7799ee">
243269
<td colspan=3 valign=bottom>&nbsp;<br>
@@ -1048,6 +1074,37 @@ class C: "New-style class"
10481074
expected = 'C in module %s object' % __name__
10491075
self.assertIn(expected, pydoc.render_doc(c))
10501076

1077+
def test_generic_alias(self):
1078+
self.assertEqual(pydoc.describe(typing.List[int]), '_GenericAlias')
1079+
doc = pydoc.render_doc(typing.List[int], renderer=pydoc.plaintext)
1080+
self.assertIn('_GenericAlias in module typing', doc)
1081+
self.assertIn('\nclass list(object)', doc)
1082+
self.assertIn(list.__doc__.strip().splitlines()[0], doc)
1083+
1084+
self.assertEqual(pydoc.describe(list[int]), 'GenericAlias')
1085+
doc = pydoc.render_doc(list[int], renderer=pydoc.plaintext)
1086+
self.assertIn('GenericAlias in module builtins', doc)
1087+
self.assertIn('\nclass list(object)', doc)
1088+
self.assertIn(list.__doc__.strip().splitlines()[0], doc)
1089+
1090+
def test_union_type(self):
1091+
self.assertEqual(pydoc.describe(typing.Union[int, str]), '_UnionGenericAlias')
1092+
doc = pydoc.render_doc(typing.Union[int, str], renderer=pydoc.plaintext)
1093+
self.assertIn('_UnionGenericAlias in module typing', doc)
1094+
self.assertIn('\ntyping.Union', doc)
1095+
if typing.Union.__doc__:
1096+
self.assertIn(typing.Union.__doc__.strip().splitlines()[0], doc)
1097+
1098+
def test_special_form(self):
1099+
self.assertEqual(pydoc.describe(typing.Any), '_SpecialForm')
1100+
doc = pydoc.render_doc(typing.Any, renderer=pydoc.plaintext)
1101+
self.assertIn('_SpecialForm in module typing', doc)
1102+
if typing.Any.__doc__:
1103+
self.assertIn('\ntyping.Any', doc)
1104+
self.assertIn(typing.Any.__doc__.strip().splitlines()[0], doc)
1105+
else:
1106+
self.assertIn('\nclass _SpecialForm(_Final)', doc)
1107+
10511108
def test_typing_pydoc(self):
10521109
def foo(data: typing.List[typing.Any],
10531110
x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix supporting generic aliases in :mod:`pydoc`.

0 commit comments

Comments
 (0)