Skip to content

Commit 1143d03

Browse files
committed
Accept packages or package names
Closes python#7
1 parent 929c31f commit 1143d03

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

README.md

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,19 +58,27 @@ import importlib
5858
import os
5959
import pathlib
6060
import tempfile
61+
import types
6162
from typing import ContextManager, Iterator, Union
6263
from typing.io import BinaryIO
6364

6465

66+
Package = Union[str, types.ModuleType]
6567
Path = Union[str, os.PathLike]
6668

6769

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
7276
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
7482

7583

7684
def _normalize_path(path):
@@ -83,14 +91,14 @@ def _normalize_path(path):
8391
return normalized_path
8492

8593

86-
def open(module_name: str, path: Path) -> BinaryIO:
94+
def open(module_name: Package, path: Path) -> BinaryIO:
8795
"""Return a file-like object opened for binary-reading of the resource."""
8896
normalized_path = _normalize_path(path)
8997
module = _get_package(module_name)
9098
return module.__spec__.loader.open_resource(normalized_path)
9199

92100

93-
def read(module_name: str, path: Path, encoding: str = "utf-8",
101+
def read(module_name: Package, path: Path, encoding: str = "utf-8",
94102
errors: str = "strict") -> str:
95103
"""Return the decoded string of the resource.
96104
@@ -102,7 +110,7 @@ def read(module_name: str, path: Path, encoding: str = "utf-8",
102110

103111

104112
@contextlib.contextmanager
105-
def path(module_name: str, path: Path) -> Iterator[pathlib.Path]:
113+
def path(module_name: Package, path: Path) -> Iterator[pathlib.Path]:
106114
"""A context manager providing a file path object to the resource.
107115
108116
If the resource does not already exist on its own on the file system,

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy