Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/alex-ber/AlexBerUtils/llms.txt

Use this file to discover all available pages before exploring further.

fixabscwd

Changes the process working directory to the directory containing the __main__ module’s file. This makes relative file paths in the main script resolve correctly regardless of where the process was started from. No-op when running inside a REPL, IPython notebook, or a frozen/bundled executable. Returns: None
from alexber.utils.mains import fixabscwd

if __name__ == "__main__":
    fixabscwd()
    # relative paths now work as expected
    config = open("config.yaml").read()
See the documentation article for details.

path

Returns the path callable from the appropriate importlib.resources API — built-in for Python ≥ 3.7, falling back to the importlib_resources backport for older versions. Returns: The importlib.resources.path (or backport equivalent) context-manager factory. Raises:
  • ImportWarning + re-raises ImportError — if the backport is required but not installed.
from alexber.utils.mains import path

l_path = path()
with l_path("my_package", "data.json") as p:
    data = open(p).read()

load_env

Loads environment variables from a .env file, with support for packaged resources (eggs, wheels, zips).
ENV_PCK
str
Python package that contains the .env file. When provided (and dotenv_path / stream are absent), importlib.resources is used to resolve the file path.
ENV_NAME
str
default:".env"
Name of the .env file inside ENV_PCK.
dotenv_path
str | Path
Absolute or relative path to a .env file. When given, ENV_PCK is ignored.
stream
StringIO
In-memory .env content. When given, ENV_PCK is ignored.
**kwargs
Any
All remaining kwargs are forwarded directly to python-dotenv’s load_dotenv().
Returns: None Raises:
  • ImportWarning + ImportError — if python-dotenv is not installed.
  • ValueError — if ENV_PCK is empty when it is the only resolution path.
from alexber.utils.mains import load_env

# from a package resource
load_env(ENV_PCK="my_app", ENV_NAME="production.env")

# from an explicit path
load_env(dotenv_path="/etc/my_app/.env", override=True)

BaseOsEnvrion

Base class for os.environ fixup helpers. Parses separator configuration and the list of environment variable keys to operate on.
ENV_KEYS
str
required
Comma-separated (by default) list of os.environ key names to process.
ENV_KEY_SEP
str
default:","
Separator used between key names in ENV_KEYS.
ENV_SEP
str
default:"os.path.sep"
Path separator used within path values (e.g. / on POSIX).
ENV_DELIM_SEP
str
default:"os.pathsep"
Delimiter separating multiple paths inside a single environment variable value (e.g. : on POSIX, ; on Windows).
Raises:
  • ValueError — if ENV_KEYS is missing or empty.
from alexber.utils.mains import BaseOsEnvrion

base = BaseOsEnvrion(ENV_KEYS="PATH,PYTHONPATH")

OsEnvrionPathExpender

Extends BaseOsEnvrion to prepend the absolute path of a reference package’s root to relative paths stored in environment variables. Inherits all BaseOsEnvrion parameters, plus:
ENV_MAIN_PCK
str
required
The installed Python package whose __init__.py location is used to compute the absolute prefix.
Raises:
  • ValueError — if ENV_MAIN_PCK is missing.

OsEnvrionPathExpender.fix_abs_path

Iterates over every key in ENV_KEYS, splits its value into individual relative paths, prepends the computed absolute prefix, and writes the result back to os.environ. Returns: None
from alexber.utils.mains import OsEnvrionPathExpender

expander = OsEnvrionPathExpender(
    ENV_KEYS="MY_DATA_DIR",
    ENV_MAIN_PCK="my_package",
)
expander.fix_abs_path()

OsEnvrionPathRetry

Extends BaseOsEnvrion to make Windows-style paths (e.g. C:\foo\bar) work on Linux by stripping the drive letter when the path does not exist on the current filesystem. Inherits all BaseOsEnvrion parameters.

OsEnvrionPathRetry.fix_retry_path

For each path value under every ENV_KEYS key: if the path does not exist and has a Windows drive prefix (e.g. C:), the drive is stripped and the POSIX remainder is used instead. Returns: None
from alexber.utils.mains import OsEnvrionPathRetry

retry = OsEnvrionPathRetry(ENV_KEYS="SOME_PATH")
retry.fix_retry_path()

fix_env

Convenience function that constructs an OsEnvrionPathExpender (or a custom subclass) and calls fix_abs_path().
ENV_KEYS
str
required
Forwarded to the expander class.
ENV_MAIN_PCK
str
required
Forwarded to the expander class.
cls
type | str
default:"OsEnvrionPathExpender"
Implementation class or its fully-qualified import string. Resolved via importer() when a string is given.
**kwargs
Any
All remaining kwargs are forwarded to the class constructor.
Returns: None
from alexber.utils.mains import fix_env

fix_env(ENV_KEYS="MY_DIR", ENV_MAIN_PCK="my_package")

fix_retry_env

Convenience function that constructs an OsEnvrionPathRetry (or a custom subclass) and calls fix_retry_path().
ENV_KEYS
str
required
Forwarded to the retry class.
cls
type | str
default:"OsEnvrionPathRetry"
Implementation class or its fully-qualified import string.
**kwargs
Any
All remaining kwargs are forwarded to the class constructor.
Returns: None
from alexber.utils.mains import fix_retry_env

fix_retry_env(ENV_KEYS="SOME_PATH")

FixRelCwd

Context manager that temporarily changes the working directory to the directory containing relPackage.__file__, then restores the original directory on exit. Useful when calling a module that uses relative file paths from a different working directory.
relPackage
module
required
An imported Python package/module. The CWD is set to the directory of its __file__ attribute.
logger
logging.Logger
default:"None"
Logger instance. When None, the module-level logger is used.
Yields: The absolute path (str) to the directory. Raises: Propagates any exception from the with block after restoring the CWD.
from alexber.utils.mains import FixRelCwd
import some_package

with FixRelCwd(some_package) as pkg_dir:
    # CWD is now some_package's directory
    some_package.load_config("config.yaml")
# CWD is restored here

GuardedWorkerException

Context manager that catches exceptions in multiprocessing worker functions, preventing pool.join() from hanging forever due to unpicklable exceptions.
logger
logging.Logger
default:"None"
Logger to record the caught exception. When None, the traceback is printed to sys.stderr.
suppress
bool
default:"False"
When True, the exception is swallowed. When False (default), a plain Exception with default_exc_message is raised instead.
default_exc_message
str
default:"Worker failed"
Message for the replacement exception when suppress=False.
Yields: None Raises:
  • Exception(default_exc_message) — when suppress=False and the worker raises.
from alexber.utils.mains import GuardedWorkerException

def worker_fn(data):
    with GuardedWorkerException(logger=logger, suppress=False):
        # any exception here will be caught and re-raised as a plain Exception
        process(data)

is_iterable

Returns True if value supports iteration, excluding None, str, and bytes.
value
Any
required
The value to test.
Returns: bool
from alexber.utils.mains import is_iterable

is_iterable([1, 2, 3])   # True
is_iterable("hello")     # False
is_iterable(None)        # False
is_iterable({"a": 1})   # True

is_mapping

Returns True if value has a callable items attribute (i.e. behaves like a dict).
value
Any
required
The value to test.
Returns: bool
from alexber.utils.mains import is_mapping

is_mapping({"a": 1})  # True
is_mapping([1, 2])    # False

make_hashable

Recursively converts an object into a hashable representation so it can be used as a dict key or set element.
  • Mappings → frozenset of (make_hashable(k), make_hashable(v)) pairs
  • Iterables (non-str, non-bytes) → tuple of recursively converted elements
  • Natively hashable objects → returned as-is
  • Everything else → wrapped in HashableWrapper
obj
Any
required
The object to convert.
Returns: A hashable object (frozenset, tuple, the original object, or HashableWrapper).
from alexber.utils.mains import make_hashable

key = make_hashable({"x": [1, 2], "y": {3, 4}})
cache = {key: "result"}

HashableWrapper

Fallback wrapper that makes any object hashable by delegating __hash__ to hash(str(obj)).
obj
Any
required
The non-hashable object to wrap.

HashableWrapper.__hash__

Returns: inthash(str(self.obj)).

HashableWrapper.__eq__

Two HashableWrapper instances are equal if both wrap equal underlying objects. Returns: bool

HashableWrapper.__repr__

Returns: str"HashableWrapper(<repr of obj>)".
from alexber.utils.mains import HashableWrapper

w = HashableWrapper([1, 2, 3])
hash(w)    # works
cache = {w: "value"}