Skip to content

Commit

Permalink
Add exception
Browse files Browse the repository at this point in the history
  • Loading branch information
andersgs committed Mar 9, 2023
1 parent 4809898 commit 9b1d800
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
48 changes: 41 additions & 7 deletions src/rezzie/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import sys
import pathlib
from .exceptions import RezzieWasUnableToAccessResource

if sys.version_info < (3, 9):
from importlib_resources import files
Expand All @@ -20,9 +21,25 @@ def get_path(module: str, *path: str) -> pathlib.Path:
Return a path to a resource shipped with your package. The path will last
for the duration of test execution, and will be cleaned up automatically.
This code works with versions of python 3.6 to 3.8.
Args:
module: The name of the module containing the resource.
path: The path to the resource, relative to the module.
Returns:
A pathlib.Path object pointing to the resource.
Raises:
RezzieWasUnableToAccessResource: Raised when Rezzie is unable to
access a resource.
"""
path = files(module).joinpath(*path)
return path
try:
path = files(module).joinpath(*path)
return path
except Exception as error:
raise RezzieWasUnableToAccessResource(
"Unable to access resource"
) from error

else:
import atexit
Expand All @@ -34,9 +51,26 @@ def get_path(module: str, *path: setattr) -> pathlib.Path:
Return a path to a resource shipped with your package. The path will last
for the duration of test execution, and will be cleaned up automatically.
This requires Python 3.9 or later.
Args:
module: The name of the module containing the resource.
path: The path to the resource, relative to the module.
Returns:
A pathlib.Path object pointing to the resource.
Raises:
RezzieWasUnableToAccessResource: Raised when Rezzie is unable to
access a resource.
"""
file_manager = ExitStack()
atexit.register(file_manager.close)
ref = importlib.resources.files(module).joinpath(*path)
path = file_manager.enter_context(importlib.resources.as_file(ref))
return path
try:
file_manager = ExitStack()
atexit.register(file_manager.close)
ref = importlib.resources.files(module).joinpath(*path)
path = file_manager.enter_context(importlib.resources.as_file(ref))
return path
except Exception as error:
file_manager.close()
raise RezzieWasUnableToAccessResource(
"Unable to access resource"
) from error
9 changes: 9 additions & 0 deletions src/rezzie/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""
Rezzie exceptions
"""


class RezzieWasUnableToAccessResource(Exception):
"""
Raised when Rezzie is unable to access a resource.
"""

0 comments on commit 9b1d800

Please sign in to comment.