10
10
import sys
11
11
import tokenize
12
12
from re import Pattern
13
- from typing import TYPE_CHECKING
13
+ from typing import TYPE_CHECKING , Any
14
14
15
15
from astroid import nodes
16
16
35
35
WikiWordFilter ,
36
36
get_tokenizer ,
37
37
)
38
- except ImportError :
38
+
39
+ PYENCHANT_AVAILABLE = True
40
+ except ImportError : # pragma: no cover
39
41
enchant = None
42
+ PYENCHANT_AVAILABLE = False
40
43
41
44
class EmailFilter : # type: ignore[no-redef]
42
45
...
@@ -62,17 +65,33 @@ def get_tokenizer(
62
65
return Filter ()
63
66
64
67
65
- if enchant is not None :
66
- br = enchant .Broker ()
67
- dicts = br .list_dicts ()
68
- dict_choices = ["" ] + [d [0 ] for d in dicts ]
69
- dicts = [f"{ d [0 ]} ({ d [1 ].name } )" for d in dicts ]
70
- dicts = ", " .join (dicts )
71
- instr = ""
72
- else :
73
- dicts = "none"
74
- dict_choices = ["" ]
75
- instr = " To make it work, install the 'python-enchant' package."
68
+ def _get_enchant_dicts () -> list [tuple [Any , enchant .ProviderDesc ]]:
69
+ # Broker().list_dicts() is not typed in enchant, but it does return tuples
70
+ return enchant .Broker ().list_dicts () if PYENCHANT_AVAILABLE else [] # type: ignore[no-any-return]
71
+
72
+
73
+ def _get_enchant_dict_choices (
74
+ inner_enchant_dicts : list [tuple [Any , enchant .ProviderDesc ]]
75
+ ) -> list [str ]:
76
+ return ["" ] + [d [0 ] for d in inner_enchant_dicts ]
77
+
78
+
79
+ def _get_enchant_dict_help (
80
+ inner_enchant_dicts : list [tuple [Any , enchant .ProviderDesc ]],
81
+ pyenchant_available : bool ,
82
+ ) -> str :
83
+ if inner_enchant_dicts :
84
+ dict_as_str = [f"{ d [0 ]} ({ d [1 ].name } )" for d in inner_enchant_dicts ]
85
+ enchant_help = f"Available dictionaries: { ', ' .join (dict_as_str )} "
86
+ else :
87
+ enchant_help = "No available dictionaries : You need to install "
88
+ if not pyenchant_available :
89
+ enchant_help += "both the python package and "
90
+ enchant_help += "the system dependency for enchant to work."
91
+ return f"Spelling dictionary name. { enchant_help } ."
92
+
93
+
94
+ enchant_dicts = _get_enchant_dicts ()
76
95
77
96
78
97
class WordsWithDigitsFilter (Filter ): # type: ignore[misc]
@@ -237,9 +256,8 @@ class SpellingChecker(BaseTokenChecker):
237
256
"default" : "" ,
238
257
"type" : "choice" ,
239
258
"metavar" : "<dict name>" ,
240
- "choices" : dict_choices ,
241
- "help" : "Spelling dictionary name. "
242
- f"Available dictionaries: { dicts } .{ instr } " ,
259
+ "choices" : _get_enchant_dict_choices (enchant_dicts ),
260
+ "help" : _get_enchant_dict_help (enchant_dicts , PYENCHANT_AVAILABLE ),
243
261
},
244
262
),
245
263
(
@@ -297,7 +315,7 @@ class SpellingChecker(BaseTokenChecker):
297
315
298
316
def open (self ) -> None :
299
317
self .initialized = False
300
- if enchant is None :
318
+ if not PYENCHANT_AVAILABLE :
301
319
return
302
320
dict_name = self .linter .config .spelling_dict
303
321
if not dict_name :
0 commit comments