|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import textwrap |
| 4 | +import warnings |
| 5 | +from collections.abc import Generator |
| 6 | +from contextlib import contextmanager |
| 7 | +from types import GenericAlias |
| 8 | +from typing import Literal |
| 9 | + |
| 10 | +import dotenv |
| 11 | +from pydantic.fields import FieldInfo |
| 12 | +from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict |
| 13 | + |
| 14 | +from ._utils import copy_func |
| 15 | + |
| 16 | + |
| 17 | +def _type_str(field: FieldInfo) -> str: |
| 18 | + return ( |
| 19 | + field.annotation.__name__ |
| 20 | + if isinstance(field.annotation, type) and not isinstance(field.annotation, GenericAlias) |
| 21 | + else str(field.annotation) |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +_docstring_template = """Allows users to customize settings for the `{package}` package. |
| 26 | +
|
| 27 | +Settings here will generally be for advanced use-cases and should be used with caution. |
| 28 | +
|
| 29 | +For setting an option use :func:`~{package}.{name}.override` (local) or set the attributes directly (global) |
| 30 | +i.e., `{package}.{name}.my_setting = foo`. For assignment by environment variable, use the variable name in |
| 31 | +all caps with `{env_prefix}` as the prefix before import of `{package}`. |
| 32 | +""" |
| 33 | + |
| 34 | + |
| 35 | +class Settings(BaseSettings): |
| 36 | + '''Base class for package settings. |
| 37 | +
|
| 38 | + This class can be subclassed by individual packages to get package-specific settings handling. |
| 39 | + Settings will be validated on assignment thanks to Pydantic. The class requires one argument |
| 40 | + `exported_object_name` and one optional argument `docstring_style`, which will be used to construct |
| 41 | + a suitable docstring (see the examples). |
| 42 | +
|
| 43 | + Both a settings instance and its `override` method should be added to the package documentation. |
| 44 | +
|
| 45 | + Thanks to Pydantic Settings, settings values will also be loaded from environment variables or `.env` |
| 46 | + files. Environment variables must be prefixex with `$PACKAGE_NAME_` to take effect, where `$PACKAGE_NAME` |
| 47 | + is the name of the package of the subclass. This can be overridden by passing `env_prefix=CUSTOMPREFIX` |
| 48 | + as class argument. |
| 49 | +
|
| 50 | + Examples: |
| 51 | + >>> from typing import Annotated |
| 52 | + ... from pydantic import Field |
| 53 | + ... from scverse_misc import Settings |
| 54 | + ... |
| 55 | + ... |
| 56 | + ... class MySettings(Settings, exported_object_name="settings", docstring_style="numpy"): |
| 57 | + ... eps: Annotated[float, Field(gt=0, lt=1)] = 1e-8 |
| 58 | + ... """Small epsilon for numerical stability.""" |
| 59 | + ... |
| 60 | + ... use_optional_feature: bool = False |
| 61 | + ... """Whether to use the optional feature.""" |
| 62 | + ... |
| 63 | + ... |
| 64 | + ... settings = MySettings() |
| 65 | + ''' |
| 66 | + |
| 67 | + @classmethod |
| 68 | + def settings_customise_sources( |
| 69 | + cls, |
| 70 | + settings_cls: type[BaseSettings], |
| 71 | + init_settings: PydanticBaseSettingsSource, |
| 72 | + env_settings: PydanticBaseSettingsSource, |
| 73 | + dotenv_settings: PydanticBaseSettingsSource, |
| 74 | + file_secret_settings: PydanticBaseSettingsSource, |
| 75 | + ) -> tuple[PydanticBaseSettingsSource, ...]: |
| 76 | + return init_settings, env_settings, dotenv_settings |
| 77 | + |
| 78 | + @staticmethod |
| 79 | + def _get_packagename(subcls: type[Settings]) -> str: |
| 80 | + package_name = subcls.__module__ |
| 81 | + dotidx = package_name.find(".") |
| 82 | + if dotidx > -1: |
| 83 | + package_name = package_name[:dotidx] |
| 84 | + return package_name |
| 85 | + |
| 86 | + def __init_subclass__(subcls, *, exported_object_name: str, docstring_style: Literal["google", "numpy"] = "google"): |
| 87 | + if (config := subcls.__dict__.get("model_config")) is not None: |
| 88 | + if not config.get("validate_assignment", True): |
| 89 | + warnings.warn("`validate_assignment=False` is not supported, overriding.", RuntimeWarning, stacklevel=2) |
| 90 | + if not config.get("use_attribute_docstrings", True): |
| 91 | + warnings.warn( |
| 92 | + "`use_attribute_docstrings=False` is not supported, overriding.", RuntimeWarning, stacklevel=2 |
| 93 | + ) |
| 94 | + if config.get("env_file") is not None: |
| 95 | + warnings.warn( |
| 96 | + "Setting a custom env_file location is not supported, overriding.", RuntimeWarning, stacklevel=2 |
| 97 | + ) |
| 98 | + else: |
| 99 | + config = SettingsConfigDict() |
| 100 | + |
| 101 | + config["validate_assignment"] = True |
| 102 | + config["use_attribute_docstrings"] = True |
| 103 | + config["env_file"] = dotenv.find_dotenv() |
| 104 | + |
| 105 | + if not config.get("env_prefix"): |
| 106 | + config["env_prefix"] = f"{__class__._get_packagename(subcls)}_" # type: ignore[name-defined] # https://github.com/python/mypy/issues/4177 |
| 107 | + subcls.model_config = config |
| 108 | + |
| 109 | + super().__init_subclass__() |
| 110 | + |
| 111 | + @contextmanager |
| 112 | + def override(self, **kwargs: object) -> Generator[None]: |
| 113 | + """Context manager for local setting overrides. |
| 114 | +
|
| 115 | + Subclasses will get a version with a docstring detailing the available parameters. |
| 116 | + """ |
| 117 | + oldsettings = {argname: getattr(self, argname) for argname in kwargs.keys()} |
| 118 | + try: |
| 119 | + for argname, argval in kwargs.items(): |
| 120 | + setattr(self, argname, argval) |
| 121 | + yield |
| 122 | + finally: |
| 123 | + for argname, argval in reversed(oldsettings.items()): |
| 124 | + setattr(self, argname, argval) |
| 125 | + |
| 126 | + @classmethod |
| 127 | + def __pydantic_init_subclass__( # type: ignore[override] |
| 128 | + subcls, *, exported_object_name: str, docstring_style: Literal["google", "numpy"] = "google" |
| 129 | + ) -> None: |
| 130 | + subcls.__doc__ = ( |
| 131 | + _docstring_template.format( |
| 132 | + package=__class__._get_packagename(subcls), # type: ignore[name-defined] # https://github.com/python/mypy/issues/4177 |
| 133 | + name=exported_object_name, |
| 134 | + env_prefix=subcls.model_config["env_prefix"].upper(), |
| 135 | + ) |
| 136 | + + "\n\nThe following options are available:\n" |
| 137 | + ) |
| 138 | + override_doc = "Provides local override via keyword arguments as a context manager.\n\n" |
| 139 | + if docstring_style == "google": |
| 140 | + override_doc += "Args:\n" |
| 141 | + else: |
| 142 | + override_doc += "Parameters\n----------\n" |
| 143 | + for fname, field in subcls.model_fields.items(): |
| 144 | + subcls.__doc__ += f""" |
| 145 | +.. attribute:: {exported_object_name}.{fname} |
| 146 | + :type: {_type_str(field)} |
| 147 | + :value: {field.default!r}\n""" |
| 148 | + |
| 149 | + description = f"(default `{field.default!r}`) " |
| 150 | + if field.description is not None: |
| 151 | + subcls.__doc__ += f"\n{textwrap.indent(field.description, ' ')}\n" |
| 152 | + description += field.description |
| 153 | + |
| 154 | + if docstring_style == "google": |
| 155 | + override_doc += f""" {fname} ({_type_str(field)}): {textwrap.indent(description, " ")}\n""" |
| 156 | + else: |
| 157 | + override_doc += f""" |
| 158 | +{fname} : {_type_str(field)} |
| 159 | +{textwrap.indent(description, " ")}\n""" |
| 160 | + |
| 161 | + subcls.override = copy_func( # type: ignore[method-assign,type-var] |
| 162 | + subcls.override, |
| 163 | + __doc__=override_doc, |
| 164 | + __module__=subcls.__module__, |
| 165 | + __qualname__=f"{subcls.__qualname__}.override", |
| 166 | + ) |
0 commit comments