@@ -59,6 +59,7 @@ class or function within a module or module in a package. If the
59
59
import importlib ._bootstrap
60
60
import importlib ._bootstrap_external
61
61
import importlib .machinery
62
+ import importlib .metadata
62
63
import importlib .util
63
64
import inspect
64
65
import io
@@ -183,6 +184,14 @@ def _getdoc(object):
183
184
return None
184
185
return inspect .cleandoc (doc )
185
186
187
+ def _getversion (mod , name ):
188
+ try :
189
+ return importlib .metadata .version (name )
190
+ except importlib .metadata .PackageNotFoundError :
191
+ if version := getattr (mod , '__version__' , '' ):
192
+ return str (version )
193
+ return None
194
+
186
195
def getdoc (object ):
187
196
"""Get the doc string or comments for an object."""
188
197
result = _getdoc (object ) or inspect .getcomments (object )
@@ -766,8 +775,7 @@ def docmodule(self, object, name=None, mod=None, *ignored):
766
775
except TypeError :
767
776
filelink = '(built-in)'
768
777
info = []
769
- if hasattr (object , '__version__' ):
770
- version = str (object .__version__ )
778
+ if version := _getversion (object , name ):
771
779
if version [:11 ] == '$' + 'Revision: ' and version [- 1 :] == '$' :
772
780
version = version [11 :- 1 ].strip ()
773
781
info .append ('version %s' % self .escape (version ))
@@ -1286,8 +1294,7 @@ def docmodule(self, object, name=None, mod=None):
1286
1294
contents .append (self .docother (value , key , name , maxlen = 70 ))
1287
1295
result = result + self .section ('DATA' , '\n ' .join (contents ))
1288
1296
1289
- if hasattr (object , '__version__' ):
1290
- version = str (object .__version__ )
1297
+ if version := _getversion (object , name ):
1291
1298
if version [:11 ] == '$' + 'Revision: ' and version [- 1 :] == '$' :
1292
1299
version = version [11 :- 1 ].strip ()
1293
1300
result = result + self .section ('VERSION' , version )
0 commit comments