Skip to content

File: Broken/__init__.py

Broken

Environment

Utilities for managing environment variables

Source code in Broken/__init__.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Environment:
    """Utilities for managing environment variables"""

    def __new__(cls) -> None:
        raise TypeError(f"{cls.__name__} class cannot be instantiated")

    @staticmethod
    def set(key: str, value: str | None, /) -> None:
        if (value is not None):
            os.environ[key] = str(value)

    @staticmethod
    def append(key: str, value: str | None, /, pad: str=" ") -> None:
        if (key not in os.environ):
            Environment.set(key, value)
        elif (value is not None):
            os.environ[key] += pad + str(value)

    @staticmethod
    def setdefault(key: str, value: str | None, /) -> None:
        if (value is not None):
            os.environ.setdefault(key, str(value))

    @staticmethod
    def update(**values: str | None) -> None:
        for key, value in values.items():
            Environment.set(key, value)

    @staticmethod
    def get(key: str, default: str=None, /) -> str:
        return os.getenv(key, default)

    @staticmethod
    def exists(key: str, /) -> bool:
        return (key in os.environ)

    @staticmethod
    def int(key: str, default: int=0, /) -> int:
        return int(os.getenv(key, default))

    @staticmethod
    def float(key: str, default: float=1.0, /) -> float:
        return float(os.getenv(key, default))

    @staticmethod
    def bool(key: str, default: bool=False, /) -> bool:
        value = str(os.getenv(key, default)).lower()

        if value in ("1", "true", "yes", "on"):
            return True
        elif value in ("0", "false", "no", "off"):
            return False

        raise ValueError(f"Invalid boolean value for environment variable '{key}': {value}")

    @staticmethod
    def flag(key: str, default: bool=False, /) -> bool:
        return Environment.bool(key, default)

    @staticmethod
    def unset(key: str, /) -> None:
        os.unsetenv(key)

__new__

__new__() -> None
Source code in Broken/__init__.py
15
16
def __new__(cls) -> None:
    raise TypeError(f"{cls.__name__} class cannot be instantiated")

set

set(key: str, value: str | None) -> None
Source code in Broken/__init__.py
18
19
20
21
@staticmethod
def set(key: str, value: str | None, /) -> None:
    if (value is not None):
        os.environ[key] = str(value)

append

append(
    key: str, value: str | None, /, pad: str = " "
) -> None
Source code in Broken/__init__.py
23
24
25
26
27
28
@staticmethod
def append(key: str, value: str | None, /, pad: str=" ") -> None:
    if (key not in os.environ):
        Environment.set(key, value)
    elif (value is not None):
        os.environ[key] += pad + str(value)

setdefault

setdefault(key: str, value: str | None) -> None
Source code in Broken/__init__.py
30
31
32
33
@staticmethod
def setdefault(key: str, value: str | None, /) -> None:
    if (value is not None):
        os.environ.setdefault(key, str(value))

update

update(**values: str | None) -> None
Source code in Broken/__init__.py
35
36
37
38
@staticmethod
def update(**values: str | None) -> None:
    for key, value in values.items():
        Environment.set(key, value)

get

get(key: str, default: str = None) -> str
Source code in Broken/__init__.py
40
41
42
@staticmethod
def get(key: str, default: str=None, /) -> str:
    return os.getenv(key, default)

exists

exists(key: str) -> bool
Source code in Broken/__init__.py
44
45
46
@staticmethod
def exists(key: str, /) -> bool:
    return (key in os.environ)

int

int(key: str, default: int = 0) -> int
Source code in Broken/__init__.py
48
49
50
@staticmethod
def int(key: str, default: int=0, /) -> int:
    return int(os.getenv(key, default))

float

float(key: str, default: float = 1.0) -> float
Source code in Broken/__init__.py
52
53
54
@staticmethod
def float(key: str, default: float=1.0, /) -> float:
    return float(os.getenv(key, default))

bool

bool(key: str, default: bool = False) -> bool
Source code in Broken/__init__.py
56
57
58
59
60
61
62
63
64
65
@staticmethod
def bool(key: str, default: bool=False, /) -> bool:
    value = str(os.getenv(key, default)).lower()

    if value in ("1", "true", "yes", "on"):
        return True
    elif value in ("0", "false", "no", "off"):
        return False

    raise ValueError(f"Invalid boolean value for environment variable '{key}': {value}")

flag

flag(key: str, default: bool = False) -> bool
Source code in Broken/__init__.py
67
68
69
@staticmethod
def flag(key: str, default: bool=False, /) -> bool:
    return Environment.bool(key, default)

unset

unset(key: str) -> None
Source code in Broken/__init__.py
71
72
73
@staticmethod
def unset(key: str, /) -> None:
    os.unsetenv(key)

Runtime

Information about the current runtime environment

Source code in Broken/__init__.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
class Runtime:
    """Information about the current runtime environment"""

    Version: str = __version__
    """The version of the Broken library, and subsequently all projects"""

    # # Bitness

    Bitness: int = (struct.calcsize("P") * 8)
    """The word size of the Python interpreter (32, 64 bits)"""

    Python32: bool = (Bitness == 32)
    """True if running on a 32-bit Python interpreter"""

    Python64: bool = (Bitness == 64)
    """True if running on a 64-bit Python interpreter"""

    # # Runtime environments

    PyInstaller: bool = bool(getattr(sys, "frozen", False))
    """True if running from a PyInstaller binary build (https://github.com/pyinstaller/pyinstaller)"""

    Nuitka: bool = ("__compiled__" in globals())
    """True if running from a Nuitka binary build (https://github.com/Nuitka/Nuitka)"""

    PyApp: bool = Environment.exists("PYAPP")
    """True if running as a PyApp release (https://github.com/ofek/pyapp)"""

    PyPI: bool = any((part in __file__.lower() for part in ("site-packages", "dist-packages")))
    """True if running as a installed package from PyPI (https://brokensrc.dev/get/pypi/)"""

    Binary: bool = (PyInstaller or Nuitka or PyApp)
    """True if running from any executable build (PyInstaller, Nuitka, PyApp)"""

    Release: bool = (Binary or PyPI)
    """True if running from any static final release build (PyInstaller, Nuitka, PyApp, PyPI)"""

    Source: bool = (not Release)
    """True if running directly from the source code (https://brokensrc.dev/get/source/)"""

    Method: str = (Source and "Source") or (Binary and "Binary") or (PyPI and "PyPI")
    """The runtime environment of the current project release (Source, Release, PyPI)"""

    # # Special and Containers

    Docker: bool = Path("/.dockerenv").exists()
    """True if running from a Docker container"""

    GitHub: bool = Environment.exists("GITHUB_ACTIONS")
    """True if running in a GitHub Actions CI environment (https://github.com/features/actions)"""

    WSL: bool = Path("/usr/lib/wsl/lib").exists()
    """True if running in Windows Subsystem for Linux (https://learn.microsoft.com/en-us/windows/wsl/about)"""

    Interactive: bool = sys.stdout.isatty()
    """True if running in an interactive terminal session (user can input)"""

Version

Version: str = __version__

The version of the Broken library, and subsequently all projects

Bitness

Bitness: int = struct.calcsize('P') * 8

The word size of the Python interpreter (32, 64 bits)

Python32

Python32: bool = Bitness == 32

True if running on a 32-bit Python interpreter

Python64

Python64: bool = Bitness == 64

True if running on a 64-bit Python interpreter

PyInstaller

PyInstaller: bool = bool(getattr(sys, 'frozen', False))

True if running from a PyInstaller binary build (https://github.com/pyinstaller/pyinstaller)

Nuitka

Nuitka: bool = '__compiled__' in globals()

True if running from a Nuitka binary build (https://github.com/Nuitka/Nuitka)

PyApp

PyApp: bool = Environment.exists('PYAPP')

True if running as a PyApp release (https://github.com/ofek/pyapp)

PyPI

PyPI: bool = any(
    part in __file__.lower()
    for part in ("site-packages", "dist-packages")
)

True if running as a installed package from PyPI (https://brokensrc.dev/get/pypi/)

Binary

Binary: bool = PyInstaller or Nuitka or PyApp

True if running from any executable build (PyInstaller, Nuitka, PyApp)

Release

Release: bool = Binary or PyPI

True if running from any static final release build (PyInstaller, Nuitka, PyApp, PyPI)

Source

Source: bool = not Release

True if running directly from the source code (https://brokensrc.dev/get/source/)

Method

Method: str = (
    Source
    and "Source"
    or Binary
    and "Binary"
    or PyPI
    and "PyPI"
)

The runtime environment of the current project release (Source, Release, PyPI)

Docker

Docker: bool = Path('/.dockerenv').exists()

True if running from a Docker container

GitHub

GitHub: bool = Environment.exists('GITHUB_ACTIONS')

True if running in a GitHub Actions CI environment (https://github.com/features/actions)

WSL

WSL: bool = Path('/usr/lib/wsl/lib').exists()

True if running in Windows Subsystem for Linux (https://learn.microsoft.com/en-us/windows/wsl/about)

Interactive

Interactive: bool = sys.stdout.isatty()

True if running in an interactive terminal session (user can input)

Tools

Shortcuts to common tools and utilities

Source code in Broken/__init__.py
179
180
181
182
183
184
185
186
187
188
189
class Tools:
    """Shortcuts to common tools and utilities"""

    python: Path = Path(sys.executable)
    """The current Python interpreter executable"""

    uv: list[str, Path] = [python, "-m", "uv"]
    """Entry point for the uv package manager (https://github.com/astral-sh/uv)"""

    pip: list[str, Path] = [python, "-m", "uv", "pip"]
    """Entry point for pip"""

python

python: Path = Path(sys.executable)

The current Python interpreter executable

uv

uv: list[str, Path] = [python, '-m', 'uv']

Entry point for the uv package manager (https://github.com/astral-sh/uv)

pip

pip: list[str, Path] = [python, '-m', 'uv', 'pip']

Entry point for pip

BROKEN

BROKEN = BrokenProject(
    PACKAGE=__file__,
    APP_NAME="Broken",
    APP_AUTHOR="BrokenSource",
    RESOURCES=BrokenResources,
)

The main library's BrokenProject instance

PROJECT

PROJECT: BrokenProject = BROKEN

The first BrokenProject initialized after (but including) BROKEN itself