create get_resource_path function

This commit is contained in:
Izalia Mae 2024-04-19 15:36:51 -04:00
parent d341950caa
commit f5c7e9102e
3 changed files with 34 additions and 0 deletions

View file

@ -45,6 +45,7 @@ from .misc import (
deprecated,
get_object_name,
get_object_properties,
get_resource_path,
get_top_domain,
http_request,
is_loop_running,

View file

@ -22,6 +22,26 @@ from urllib.request import Request, urlopen
from . import __version__
from .enums import FileSizeUnit, HttpMethod
try:
from importlib.resources import files as pkgfiles
except ImportError:
# this is a mess and I'm now debating my decision to never have outside dependencies
# outside of docs and dev stuff
import inspect
from importlib import import_module
from importlib.resources.abc import Traversable
from types import ModuleType
def pkgfiles(anchor: str | ModuleType | None = None) -> Traversable:
if anchor is None:
raise ValueError("A module or name must be specified")
if isinstance(anchor, str):
anchor = import_module(anchor)
return Path(inspect.getfile(anchor)).parent
try:
from typing import Self
@ -201,6 +221,18 @@ def get_object_properties(
yield key, value
def get_resource_path(module: str, path: str | None = None) -> Path:
"""
Get a path to a module resource
:param module: Name of the module to get the resource from
:param path: Path of the resource starting from the path of the module
"""
new_path = Path(str(pkgfiles(module)))
return new_path.joinpath(path.lstrip("/")) if path is not None else new_path
def get_top_domain(domain: str) -> str:
'''
Get the main domain from a string. The top-level domain list is cached as

View file

@ -17,6 +17,7 @@ Functions
.. autodecorator:: blib.deprecated
.. autofunction:: blib.get_object_name
.. autofunction:: blib.get_object_properties
.. autofunction:: blib.get_resource_path
.. autofunction:: blib.get_top_domain
.. autofunction:: blib.http_request
.. autofunction:: blib.is_loop_running