@@ -58,19 +58,27 @@ import importlib
58
58
import os
59
59
import pathlib
60
60
import tempfile
61
+ import types
61
62
from typing import ContextManager, Iterator, Union
62
63
from typing.io import BinaryIO
63
64
64
65
66
+ Package = Union[str , types.ModuleType]
65
67
Path = Union[str , os.PathLike]
66
68
67
69
68
- def _get_package (module_name ):
69
- module = importlib.import_module(module_name)
70
- if module.__spec__ .submodule_search_locations is None :
71
- raise TypeError (f " { module_name!r } is not a package " )
70
+ def _get_package (package ):
71
+ if hasattr (package, ' __spec__' ):
72
+ if package.__spec__ .submodule_search_locations is None :
73
+ raise TypeError (f " { package.__spec__ .name!r } is not a package " )
74
+ else :
75
+ return package
72
76
else :
73
- return module
77
+ module = importlib.import_module(package_name)
78
+ if module.__spec__ .submodule_search_locations is None :
79
+ raise TypeError (f " { package_name!r } is not a package " )
80
+ else :
81
+ return module
74
82
75
83
76
84
def _normalize_path (path ):
@@ -83,14 +91,14 @@ def _normalize_path(path):
83
91
return normalized_path
84
92
85
93
86
- def open (module_name : str , path : Path) -> BinaryIO:
94
+ def open (module_name : Package , path : Path) -> BinaryIO:
87
95
""" Return a file-like object opened for binary-reading of the resource."""
88
96
normalized_path = _normalize_path(path)
89
97
module = _get_package(module_name)
90
98
return module.__spec__ .loader.open_resource(normalized_path)
91
99
92
100
93
- def read (module_name : str , path : Path, encoding : str = " utf-8" ,
101
+ def read (module_name : Package , path : Path, encoding : str = " utf-8" ,
94
102
errors : str = " strict" ) -> str :
95
103
""" Return the decoded string of the resource.
96
104
@@ -102,7 +110,7 @@ def read(module_name: str, path: Path, encoding: str = "utf-8",
102
110
103
111
104
112
@contextlib.contextmanager
105
- def path (module_name : str , path : Path) -> Iterator[pathlib.Path]:
113
+ def path (module_name : Package , path : Path) -> Iterator[pathlib.Path]:
106
114
""" A context manager providing a file path object to the resource.
107
115
108
116
If the resource does not already exist on its own on the file system,
0 commit comments