Skip to content

Commit 9ab15fc

Browse files
committed
Create nbstata/_resources.py
1 parent 3de640a commit 9ab15fc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

nbstata/_resources.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
Zip-safe, modern resource helpers for Python 3.10+ using importlib.resources.
3+
Use these in place of pkg_resources.resource_filename / resource_string.
4+
"""
5+
from __future__ import annotations
6+
from contextlib import contextmanager
7+
from importlib.resources import files, as_file
8+
from pathlib import Path
9+
from typing import Iterator
10+
11+
PACKAGE = "nbstata"
12+
13+
def read_text(relpath: str, package: str = PACKAGE) -> str:
14+
"""Read a packaged text resource."""
15+
return (files(package) / relpath).read_text()
16+
17+
def read_bytes(relpath: str, package: str = PACKAGE) -> bytes:
18+
"""Read a packaged binary resource."""
19+
return (files(package) / relpath).read_bytes()
20+
21+
@contextmanager
22+
def resource_path(relpath: str, package: str = PACKAGE) -> Iterator[Path]:
23+
"""
24+
Context manager yielding a temporary real filesystem Path for a packaged
25+
resource. This mirrors pkg_resources.resource_filename semantics but is
26+
zip-safe and deprecation-proof.
27+
"""
28+
with as_file(files(package) / relpath) as p:
29+
yield p
30+
31+
def resource_strpath(relpath: str, package: str = PACKAGE) -> str:
32+
"""Return a string path for cases that strictly want str over Path."""
33+
with resource_path(relpath, package) as p:
34+
return str(p)

0 commit comments

Comments
 (0)