10
10
import sys
11
11
from collections import ChainMap
12
12
from contextlib import suppress
13
- from typing import Any , BinaryIO , Iterator , Mapping , Optional , Tuple
13
+ from typing import TYPE_CHECKING , Any , BinaryIO , Iterator , Mapping
14
14
15
15
from griffe .agents .extensions import load_extensions
16
16
from griffe .collections import LinesCollection , ModulesCollection
17
17
from griffe .docstrings .parsers import Parser
18
18
from griffe .exceptions import AliasResolutionError
19
19
from griffe .loader import GriffeLoader
20
20
from griffe .logger import patch_loggers
21
- from markdown import Markdown
22
21
from mkdocstrings .extension import PluginError
23
22
from mkdocstrings .handlers .base import BaseHandler , CollectionError , CollectorItem
24
23
from mkdocstrings .inventory import Inventory
25
24
from mkdocstrings .loggers import get_logger
26
25
27
26
from mkdocstrings_handlers .python import rendering
28
27
28
+ if TYPE_CHECKING :
29
+ from markdown import Markdown
30
+
31
+
29
32
if sys .version_info >= (3 , 11 ):
30
33
from contextlib import chdir
31
34
else :
32
35
# TODO: remove once support for Python 3.10 is dropped
33
36
from contextlib import contextmanager
34
37
35
- @contextmanager # noqa: WPS440
36
- def chdir (path : str ): # noqa: D103,WPS440
38
+ @contextmanager
39
+ def chdir (path : str ) -> Iterator [ None ] : # noqa: D103
37
40
old_wd = os .getcwd ()
38
41
os .chdir (path )
39
42
try :
@@ -162,10 +165,14 @@ class PythonHandler(BaseHandler):
162
165
163
166
The modules must be listed as an array of strings. Default: `None`.
164
167
165
- """ # noqa: E501
168
+ """
166
169
167
170
def __init__ (
168
- self , * args : Any , config_file_path : str | None = None , paths : list [str ] | None = None , ** kwargs : Any
171
+ self ,
172
+ * args : Any ,
173
+ config_file_path : str | None = None ,
174
+ paths : list [str ] | None = None ,
175
+ ** kwargs : Any ,
169
176
) -> None :
170
177
"""Initialize the handler.
171
178
@@ -186,9 +193,8 @@ def __init__(
186
193
paths .append (os .path .dirname (config_file_path ))
187
194
search_paths = [path for path in sys .path if path ] # eliminate empty path
188
195
for path in reversed (paths ):
189
- if not os .path .isabs (path ):
190
- if config_file_path :
191
- path = os .path .abspath (os .path .join (os .path .dirname (config_file_path ), path ))
196
+ if not os .path .isabs (path ) and config_file_path :
197
+ path = os .path .abspath (os .path .join (os .path .dirname (config_file_path ), path )) # noqa: PLW2901
192
198
if path not in search_paths :
193
199
search_paths .insert (0 , path )
194
200
self ._paths = search_paths
@@ -200,10 +206,10 @@ def load_inventory(
200
206
cls ,
201
207
in_file : BinaryIO ,
202
208
url : str ,
203
- base_url : Optional [ str ] = None ,
209
+ base_url : str | None = None ,
204
210
domains : list [str ] | None = None ,
205
- ** kwargs : Any ,
206
- ) -> Iterator [Tuple [str , str ]]:
211
+ ** kwargs : Any , # noqa: ARG003
212
+ ) -> Iterator [tuple [str , str ]]:
207
213
"""Yield items and their URLs from an inventory file streamed from `in_file`.
208
214
209
215
This implements mkdocstrings' `load_inventory` "protocol" (see [`mkdocstrings.plugin`][mkdocstrings.plugin]).
@@ -222,10 +228,10 @@ def load_inventory(
222
228
if base_url is None :
223
229
base_url = posixpath .dirname (url )
224
230
225
- for item in Inventory .parse_sphinx (in_file , domain_filter = domains ).values (): # noqa: WPS526
231
+ for item in Inventory .parse_sphinx (in_file , domain_filter = domains ).values ():
226
232
yield item .name , posixpath .join (base_url , item .uri )
227
233
228
- def collect (self , identifier : str , config : Mapping [str , Any ]) -> CollectorItem : # noqa: D102,WPS231
234
+ def collect (self , identifier : str , config : Mapping [str , Any ]) -> CollectorItem : # noqa: D102
229
235
module_name = identifier .split ("." , 1 )[0 ]
230
236
unknown_module = module_name not in self ._modules_collection
231
237
if config .get ("fallback" , False ) and unknown_module :
@@ -247,23 +253,24 @@ def collect(self, identifier: str, config: Mapping[str, Any]) -> CollectorItem:
247
253
modules_collection = self ._modules_collection ,
248
254
lines_collection = self ._lines_collection ,
249
255
)
250
- try : # noqa: WPS229 we expect one type of exception, and want to fail on the first one
256
+ try :
251
257
for pre_loaded_module in final_config .get ("preload_modules" ) or []:
252
258
if pre_loaded_module not in self ._modules_collection :
253
259
loader .load_module (pre_loaded_module )
254
260
loader .load_module (module_name )
255
261
except ImportError as error :
256
262
raise CollectionError (str (error )) from error
257
263
unresolved , iterations = loader .resolve_aliases (
258
- implicit = False , external = final_config ["load_external_modules" ]
264
+ implicit = False ,
265
+ external = final_config ["load_external_modules" ],
259
266
)
260
267
if unresolved :
261
268
logger .debug (f"{ len (unresolved )} aliases were still unresolved after { iterations } iterations" )
262
269
logger .debug (f"Unresolved aliases: { ', ' .join (sorted (unresolved ))} " )
263
270
264
271
try :
265
272
doc_object = self ._modules_collection [identifier ]
266
- except KeyError as error : # noqa: WPS440
273
+ except KeyError as error :
267
274
raise CollectionError (f"{ identifier } could not be found" ) from error
268
275
269
276
if not unknown_module :
@@ -287,9 +294,11 @@ def render(self, data: CollectorItem, config: Mapping[str, Any]) -> str: # noqa
287
294
heading_level = final_config ["heading_level" ]
288
295
try :
289
296
final_config ["members_order" ] = rendering .Order (final_config ["members_order" ])
290
- except ValueError :
297
+ except ValueError as error :
291
298
choices = "', '" .join (item .value for item in rendering .Order )
292
- raise PluginError (f"Unknown members_order '{ final_config ['members_order' ]} ', choose between '{ choices } '." )
299
+ raise PluginError (
300
+ f"Unknown members_order '{ final_config ['members_order' ]} ', choose between '{ choices } '." ,
301
+ ) from error
293
302
294
303
if final_config ["filters" ]:
295
304
final_config ["filters" ] = [
@@ -320,11 +329,11 @@ def get_anchors(self, data: CollectorItem) -> list[str]: # noqa: D102 (ignore m
320
329
321
330
322
331
def get_handler (
323
- theme : str , # noqa: W0613 (unused argument config)
324
- custom_templates : Optional [ str ] = None ,
332
+ theme : str ,
333
+ custom_templates : str | None = None ,
325
334
config_file_path : str | None = None ,
326
335
paths : list [str ] | None = None ,
327
- ** config : Any ,
336
+ ** config : Any , # noqa: ARG001
328
337
) -> PythonHandler :
329
338
"""Simply return an instance of `PythonHandler`.
330
339
0 commit comments