Skip to content

Commit 3fbbeb3

Browse files
Copilotbact
andcommitted
Use TYPE_CHECKING pattern for nlpo3 to retain type info with lazy imports
This solves the issue of balancing type information with optional dependencies: - Imports nlpo3 types only during type checking (TYPE_CHECKING block) - Does lazy imports inside functions for runtime - Provides helpful error messages when nlpo3 is not installed - Mypy can still see and use nlpo3's type information - Module can be imported even when nlpo3 is not installed Benefits: ✅ Type checking works (mypy sees nlpo3 types) ✅ No import errors when nlpo3 is not installed ✅ Functionality works when nlpo3 is installed ✅ nlpo3 stays OUT of mypy ignore list Co-authored-by: bact <128572+bact@users.noreply.github.com>
1 parent c7074d1 commit 3fbbeb3

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

pythainlp/tokenize/nlpo3.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
import threading
77
from importlib.resources import as_file, files
88
from sys import stderr
9+
from typing import TYPE_CHECKING
910

10-
from nlpo3 import load_dict as nlpo3_load_dict
11-
from nlpo3 import segment as nlpo3_segment
11+
if TYPE_CHECKING:
12+
from nlpo3 import load_dict as nlpo3_load_dict # noqa: F401
13+
from nlpo3 import segment as nlpo3_segment # noqa: F401
1214

1315
from pythainlp.corpus.common import _THAI_WORDS_FILENAME
1416

@@ -25,6 +27,13 @@ def _ensure_default_dict_loaded():
2527
The context manager is kept alive for the lifetime of the program
2628
to prevent cleanup of temporary files while the dictionary is in use.
2729
"""
30+
try:
31+
from nlpo3 import load_dict as nlpo3_load_dict
32+
except ImportError as ex:
33+
raise ImportError(
34+
"nlpo3 is not installed. Install it with: pip install nlpo3"
35+
) from ex
36+
2837
global _NLPO3_DEFAULT_DICT, _dict_file_ctx
2938
if _NLPO3_DEFAULT_DICT is None:
3039
with _load_lock:
@@ -57,6 +66,13 @@ def load_dict(file_path: str, dict_name: str) -> bool:
5766
* \
5867
https://github.com/PyThaiNLP/nlpo3
5968
"""
69+
try:
70+
from nlpo3 import load_dict as nlpo3_load_dict
71+
except ImportError as ex:
72+
raise ImportError(
73+
"nlpo3 is not installed. Install it with: pip install nlpo3"
74+
) from ex
75+
6076
msg, success = nlpo3_load_dict(file_path=file_path, dict_name=dict_name)
6177
if not success:
6278
print(msg, file=stderr)
@@ -87,6 +103,13 @@ def segment(
87103
* \
88104
https://github.com/PyThaiNLP/nlpo3
89105
"""
106+
try:
107+
from nlpo3 import segment as nlpo3_segment
108+
except ImportError as ex:
109+
raise ImportError(
110+
"nlpo3 is not installed. Install it with: pip install nlpo3"
111+
) from ex
112+
90113
# Ensure default dict is loaded if it's being used
91114
if custom_dict == _NLPO3_DEFAULT_DICT_NAME:
92115
_ensure_default_dict_loaded()

0 commit comments

Comments
 (0)