Skip to content

Commit b637f0a

Browse files
committed
Fix module import error and add detailed error message.
1 parent cba6134 commit b637f0a

File tree

4 files changed

+23
-8
lines changed

4 files changed

+23
-8
lines changed

pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "stubdoc"
3-
version = "0.1.5"
3+
version = "0.1.6"
44
description = ""
55
authors = ["simon-ritchie"]
66
license = "MIT LICENSE"

stubdoc/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
__version__: str = '0.1.5'
1+
__version__: str = '0.1.6'
22
from stubdoc.stubdoc import add_docstring_to_stubfile

stubdoc/stubdoc.py

+17-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""The module that implements core functions.
22
"""
33

4+
import sys
5+
import os
46
import re
57
import inspect
68
import importlib
@@ -401,12 +403,21 @@ def _read_module(module_path: str) -> ModuleType:
401403
module : ModuleType
402404
Read module.
403405
"""
404-
name: str = module_path.replace('.py', '')
405-
name = name.replace('/', '.')
406-
name = name.replace('\\', '.')
407-
while name.startswith('.'):
408-
name = name.replace('.', '', 1)
409-
module: ModuleType = importlib.import_module(name)
406+
file_name: str = os.path.basename(module_path)
407+
dir_path: str = module_path.replace(file_name, '', 1)
408+
sys.path.append(dir_path)
409+
package_name: str = module_path.replace('.py', '')
410+
package_name = package_name.replace('/', '.')
411+
package_name = package_name.replace('\\', '.')
412+
while package_name.startswith('.'):
413+
package_name = package_name.replace('.', '', 1)
414+
try:
415+
module: ModuleType = importlib.import_module(package_name)
416+
except Exception:
417+
raise Exception(
418+
'Specified module import failed. Please check specified path'
419+
' is not a upper level directory or root directory (need to be'
420+
f' able to import by package path style): {package_name}')
410421
return module
411422

412423

tests/test_stubdoc.py

+4
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ def test__read_module() -> None:
4646
module_path='.\\stubdoc\\stubdoc.py')
4747
assert module == stubdoc
4848

49+
with pytest.raises(Exception): # type: ignore
50+
module = stubdoc._read_module(
51+
'./not_existing_module.py')
52+
4953

5054
class _TestClass1:
5155

0 commit comments

Comments
 (0)