disdantic¶
Package initialization and unified entry point for the disdantic library.
This library simplifies registry management, polymorphic serialization, dynamic schema generation, and automatic module discovery. It provides mixins and managers to register and retrieve subclasses dynamically, making it easier to construct polymorphic data structures without manual boilerplate.
The core architecture exposes base components including RegistryMixin and
InfoMixin for behavior tracking, LazyLoader and LazyProxy for
performance-focused import loading, along with configure_logger and
package-level Settings for system initialization.
AutoImporterMixin
¶
Provides recursive package directory module scanning with cache wiping.
This mixin enables classes to dynamically discover and import submodules in a configured package hierarchy. It is typically integrated into registry systems to trigger dynamic registration of Pydantic model subclasses at runtime.
Example
.. code-block:: python
from disdantic.importer import AutoImporterMixin
class MyRegistry(AutoImporterMixin):
auto_package = "my_app.models"
auto_ignore_modules = ["my_app.models.private_model"]
# Scan and load the modules
MyRegistry.auto_import_package_modules()
Source code in src/disdantic/importer.py
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 | |
auto_ignore_modules = None
class-attribute
¶
A list of submodule names or paths to ignore during package discovery.
auto_package = None
class-attribute
¶
The target package or packages to scan for auto-importing.
auto_import_package_modules()
classmethod
¶
Walks configured module layouts recursively and imports submodules.
This method scans the configured packages, ignoring designated modules, and imports all discovered submodules to trigger dynamic registration.
:raises ValueError: If the class variable 'auto_package' has not been properly configured and settings do not specify any auto_packages. :raises ImportError: If a target package name cannot be resolved. :returns: None.
Source code in src/disdantic/importer.py
reset_importer_cache()
classmethod
¶
Purges cached system modules imported by this class.
Clears the tracked imported submodules from both sys.modules and the internal tracking set to guarantee clean test executions.
:returns: None.
Source code in src/disdantic/importer.py
DiagnosticsReport
¶
Bases: BaseModel
Aggregated health status and discovery details of all checked registries.
This class serves as the root container returned by the verification pipeline. It consolidates individual registry diagnostics, scanned packages, and import failure traces into a single report.
Examples:
.. code-block:: python
from disdantic.diagnose import verify_registries
report = verify_registries()
if not report.is_healthy:
print(f"Scanned packages: {report.scanned_packages}")
print(f"Import errors: {report.import_errors}")
Source code in src/disdantic/diagnose.py
InfoMixin
¶
Mixin providing runtime self-introspection to generate object structures.
This mixin allows subclassing models to expose their public attributes, properties, slots, and instance dicts as sanitized primitives. It recursively inspects objects, resolves lazy loaders or proxies, and handles circular reference loops and property extraction errors without raising exceptions.
Source code in src/disdantic/introspection.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
info
property
¶
Self-introspection dictionary representing the public state.
__repr__()
¶
__str__()
¶
extract_from_obj(obj, visited=None)
classmethod
¶
Parse complex objects into sanitized primitive dictionaries.
This method recursively crawls the object to extract public fields,
evaluates custom .info hooks if defined, and translates collections
or nested objects into JSON/YAML compatible dictionaries.
Source code in src/disdantic/introspection.py
info_json(*, indent=None, sort_keys=False, **kwargs)
¶
Serialize the introspection info dictionary into a valid JSON string.
Source code in src/disdantic/introspection.py
info_yaml(*, indent=None, sort_keys=False, **kwargs)
¶
Serialize the introspection info dictionary into a valid YAML string.
Source code in src/disdantic/introspection.py
LazyLoader
¶
Provides thread-safe lazy loading decorators for modules, classes, and variables.
Encapsulates static utilities to defer package imports and object instantiation. It supports lazy module resolution, injecting descriptors into classes, and wrapping functional closures inside proxy containers.
Example
.. code-block:: python
from disdantic.loading import LazyLoader
# Lazy-load a module namespace
lazy_sys = LazyLoader.load_module_proxy("sys")
Source code in src/disdantic/loading.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
class_attributes(mapping)
classmethod
¶
Bind lazy property descriptors to class attributes to defer instantiation.
Accepts a dictionary mapping attribute names to either importable module paths or factory callables, and returning a decorator for the target class.
Example
.. code-block:: python
from disdantic.loading import LazyLoader
@LazyLoader.class_attributes({"sys": "sys"})
class MyClass:
pass
instance = MyClass()
# Accessing sys will load the module lazily
print(instance.sys.path)
:param mapping: Dictionary mapping attribute names to module paths or callables. :returns: A decorator function that updates the class with lazy attributes.
Source code in src/disdantic/loading.py
definition(factory)
classmethod
¶
Create an explicit variable proxy from a functional factory closure.
Defers execution of the factory callable until attributes are accessed on the returned proxy.
Example
.. code-block:: python
from disdantic.loading import LazyLoader
proxy = LazyLoader.definition(lambda: [1, 2, 3])
# Factory remains uncalled until accessed
print(len(proxy))
:param factory: A zero-argument callable returning the target object. :returns: A LazyProxy instance wrapping the factory function.
Source code in src/disdantic/loading.py
load_module_proxy(fullname)
classmethod
¶
Generate a standard lazy loader proxy directly within the module mapping.
Resolves the module spec and registers a lazy-loading module in sys.modules, only executing the module when its attributes are accessed.
Example
.. code-block:: python
from disdantic.loading import LazyLoader
# Loads my_module lazily
my_mod = LazyLoader.load_module_proxy("my_module")
:param fullname: The fully qualified name of the module to lazy-load. :returns: A module proxy that triggers execution of the module on access. :raises ModuleNotFoundError: If the module specified by fullname cannot be resolved.
Source code in src/disdantic/loading.py
module(module_name)
classmethod
¶
Create a decorator to lazy-load module subpackages on demand.
Example
.. code-block:: python
import sys
from disdantic.loading import LazyLoader
@LazyLoader.module("disdantic")
def loading(mod):
pass
:param module_name: The fully qualified name of the package or module. :returns: A decorator function that replaces the target module with a lazy module proxy.
Source code in src/disdantic/loading.py
LazyProxy
¶
Proxy container wrapping modules or factories until an attribute is read.
Acts as a placeholder for objects whose construction is expensive or requires deferred execution. The target object is instantiated and resolved by invoking a provided factory function upon the first query of attributes, string representation, or directory listing. Resolution is fully thread-safe.
Example
.. code-block:: python
import types
from disdantic.loading import LazyProxy
def expensive_factory():
return types.SimpleNamespace(data=42)
proxy = LazyProxy(expensive_factory)
# expensive_factory is not called yet
print(proxy.data) # Triggers resolution and outputs: 42
Source code in src/disdantic/loading.py
__dir__()
¶
Return the directory list of attributes from the resolved target object.
:returns: List of attributes available on the wrapped object.
__getattr__(name)
¶
Retrieve attributes from the lazily resolved target object.
:param name: The name of the attribute to retrieve. :returns: The attribute value from the resolved object.
Source code in src/disdantic/loading.py
__init__(factory)
¶
Initialize the lazy proxy wrapper with a factory callable.
:param factory: A zero-argument callable returning the target object to wrap.
Source code in src/disdantic/loading.py
__repr__()
¶
Return a string representation of the proxy or the wrapped target.
:returns: A string indicating initialization state or the wrapped representation.
Source code in src/disdantic/loading.py
LoggingSettings
¶
Bases: BaseSettings
Settings configuration for the disdantic logging subsystem.
This class defines the configuration schema for logging, loading parameters
from environment variables prefixed with DISDANTIC__LOGGING__ or via
direct instantiation. It allows customizing the output sink, log level,
format template, OpenTelemetry integration, and thread-safe queueing.
Example
.. code-block:: python
from disdantic.logging import LoggingSettings, configure_logger
settings = LoggingSettings(
enabled=True,
level="DEBUG",
sink="stdout"
)
configure_logger(settings)
:cvar model_config: Configuration dictionary dictating environment variable prefixes and nested delimiters.
Source code in src/disdantic/logging.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 | |
PydanticClassRegistryMixin
¶
Bases: ReloadableBaseModel, RegistryMixin[type[BaseModelT]], ABC, Generic[BaseModelT]
Polymorphic serialization wrapper using dynamic tagged unions.
This class enables dynamic Pydantic model registration and builds tagged union schemas. It automatically routes JSON validation to the correct subclass using a discriminator key.
Example
.. code-block:: python
from disdantic.registry import PydanticClassRegistryMixin
from pydantic import BaseModel
class BaseMessage(PydanticClassRegistryMixin):
pass
@BaseMessage.register("text")
class TextMessage(BaseMessage):
content: str
:var schema_discriminator: The serialized tag field name used to identify the target model type.
Source code in src/disdantic/registry.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 | |
schema_discriminator = 'model_type'
class-attribute
¶
The serialized tag field name used to identify the target model type.
get_schema_discriminator()
classmethod
¶
Retrieve the active schema discriminator key.
Resolves to the class-level 'schema_discriminator' or falls back to the global settings default.
:returns: The string key name of the discriminator.
Source code in src/disdantic/registry.py
registered_classes()
classmethod
¶
Return all registered BaseModel subclasses in this registry.
Triggers auto-discovery on access if enabled.
Example
.. code-block:: python
classes = BaseMessage.registered_classes()
:raises ValueError: If no classes are registered in the registry. :returns: A tuple of registered subclass types.
Source code in src/disdantic/registry.py
RegistryDiagnostics
¶
Bases: BaseModel
Configuration, model metadata, and integrity status of a registry.
This class tracks the metadata of a single registry subclassing RegistryMixin. It records the dynamic auto-discovery configuration, registered sub-models, and any orphaned subclasses that were imported but failed to register.
Examples:
.. code-block:: python
from disdantic.diagnose import verify_registries
report = verify_registries()
for registry in report.registries:
print(f"Registry: {registry.registry_name}")
print(f"Orphaned subclasses: {registry.orphans}")
Source code in src/disdantic/diagnose.py
RegistryManager
¶
Orchestrate tracking and listing active registry namespaces globally.
This class scans the runtime subclass tree of RegistryMixin, discovers registered classes, and generates maps linking registries to their registered components.
Example
.. code-block:: python
from disdantic.registry import RegistryManager
registries = RegistryManager.list_registries()
Source code in src/disdantic/registry.py
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 | |
list_registries()
classmethod
¶
Generate a nested map of all active registries and their contents.
Scans the runtime subclass tree of RegistryMixin, discovers registered classes, and generates maps linking registries to their registered components.
Example
.. code-block:: python
mapping = RegistryManager.list_registries()
:returns: A dictionary mapping registry class names to a nested dict of registered keys and target class paths.
Source code in src/disdantic/registry.py
RegistryMixin
¶
Bases: Generic[RegistryObjT], AutoImporterMixin
Isolated registry namespace tracking across distinct base class domains.
This mixin provides base class structures with automated tracking mappings, enabling subclasses to map dynamic components and discover submodules recursively. Each registry is fully isolated to avoid leakage between unrelated interfaces. It supports registration decorators, lookup checks, and programmatic unregistration.
Example
.. code-block:: python
from disdantic.registry import RegistryMixin
class ComponentRegistry(RegistryMixin[type]):
pass
@ComponentRegistry.register("service")
class MyService:
pass
:var registry: The canonical tracking directory mapping identifiers to registered objects. :var registry_auto_discovery: Controls whether sub-module scanning is automatically triggered on access. :var registry_populated: Tracks if the auto-population routine has completed for this namespace.
Source code in src/disdantic/registry.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
registry
class-attribute
¶
The canonical tracking directory mapping identifiers to registered objects.
registry_auto_discovery = False
class-attribute
¶
Controls whether sub-module scanning is automatically triggered on access.
registry_populated = False
class-attribute
¶
Tracks if the auto-population routine has completed for this namespace.
auto_populate_registry()
classmethod
¶
Scan packages and automatically populate the registry namespace.
Discovers and imports modules dynamically if auto-discovery is enabled and the registry has not been populated yet.
Example
.. code-block:: python
MyRegistry.auto_populate_registry()
:raises ValueError: If auto-discovery is disabled on the registry class. :returns: True if the registry was newly populated, False if it was already populated.
Source code in src/disdantic/registry.py
clear_registry()
classmethod
¶
Clear all active registrations and reset import states.
Clears all mappings in canonical and lowercase registries, and resets flags so that subsequent operations can re-populate the registry.
Example
.. code-block:: python
MyRegistry.clear_registry()
:returns: None.
Source code in src/disdantic/registry.py
get_registered_object(name)
classmethod
¶
Look up a registered object by its identifier.
Looks up the given name directly in the canonical registry, falling back to a case-insensitive lookup in the lowercase registry.
Example
.. code-block:: python
obj = MyRegistry.get_registered_object("custom_name")
:param name: The identifier key of the registered object. :returns: The registered object if found, or None.
Source code in src/disdantic/registry.py
is_auto_discovery_enabled()
classmethod
¶
Determine if automatic module discovery is active for this registry.
Checks both the class-level configuration option and the fallback global settings to decide if submodules should be scanned.
:returns: True if auto-discovery is enabled, False otherwise.
Source code in src/disdantic/registry.py
is_registered(name)
classmethod
¶
Verify presence of an identifier in the registry.
Performs case-insensitive checks against the registered keys.
Example
.. code-block:: python
exists = MyRegistry.is_registered("custom_name")
:param name: The identifier key to verify. :returns: True if the identifier is registered, False otherwise.
Source code in src/disdantic/registry.py
register(name=None)
classmethod
¶
Decorate subclass implementations to register them under name keys.
Registers the decorated class or object under the specified name or list of names. If no name is provided, uses the class name.
Example
.. code-block:: python
@MyRegistry.register("custom_name")
class SubComponent:
pass
:param name: Optional registration keys. Can be a single string, a sequence of strings, or None to default to the target's name. :returns: A decorator function that registers the target object.
Source code in src/disdantic/registry.py
register_decorator(target_object, name=None)
classmethod
¶
Index target objects directly into namespace mappings.
Performs collision checking to prevent duplicate registration within the same namespace.
Example
.. code-block:: python
MyRegistry.register_decorator(MyService, name="service")
:param target_object: The class or object instance to register. :param name: Optional registration keys. Can be a single string, a sequence of strings, or None to default to the target's name. :raises ValueError: If the naming format is unsupported or if a key is not a string. :raises RegistryCollisionError: If a key is already registered. :returns: The original target object after successful registration.
Source code in src/disdantic/registry.py
registered_objects()
classmethod
¶
Retrieve all registered objects in the registry tracking frame.
Triggers auto-population if auto-discovery is enabled before returning the objects.
Example
.. code-block:: python
objects = MyRegistry.registered_objects()
:returns: A tuple of all registered objects.
Source code in src/disdantic/registry.py
unregister(name)
classmethod
¶
Remove a registered identifier from both tracking mappings.
Removes from canonical and case-insensitive mapping caches. If it is a PydanticClassRegistryMixin, triggers a core schema rebuild of the base registry class and its registered hierarchy.
Example
.. code-block:: python
MyRegistry.unregister("custom_name")
:param name: The registered identifier/token to remove. :raises ValueError: If the token is not present in the registry. :returns: None.
Source code in src/disdantic/registry.py
RegistryModelInfo
¶
Bases: BaseModel
Metadata and compilation status of a registered subclass inside a registry.
This class captures the import details, registration key, and Pydantic schema compilation status of a single model registered under a RegistryMixin class.
Examples:
.. code-block:: python
from disdantic.diagnose import verify_registries
report = verify_registries()
for registry in report.registries:
for model in registry.models:
if model.compilation_status == "error":
print(
f"Model {model.class_name} compilation error: "
f"{model.error_detail}"
)
Source code in src/disdantic/diagnose.py
ReloadableBaseModel
¶
Bases: BaseModel
Pydantic base model that dynamically cascades validation schema updates.
This class enables reloading of parent and dependent schemas when child or
dependent schemas are dynamically updated at runtime. By subclassing
ReloadableBaseModel, any modification to a child model can automatically
trigger updates to parent models that reference the child model in their
fields.
It functions by traversing Python's subclass tree and evaluating field annotations recursively, identifying models that reference a modified target. The class respects configuration flags from the global registry settings to selectively enable or disable rebuild propagation.
This class does not define any fields or class variables itself; it is intended solely as an abstract base class for reloadable models.
.. code-block:: python
from pydantic import Field
from disdantic.model import ReloadableBaseModel
class ChildModel(ReloadableBaseModel):
value: str
class ParentModel(ReloadableBaseModel):
child: ChildModel
# Rebuilding ChildModel will automatically cascade to ParentModel
ChildModel.reload_schema()
Source code in src/disdantic/model.py
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
reload_parent_schemas()
classmethod
¶
Traverses subclasses and rebuilds all dependent parent schemas.
This method scans all active subclasses of BaseModel in the runtime
registry, identifies which of those models reference the current model
class (or any of its parent classes in its MRO), and triggers a
topological rebuild of those dependents.
.. code-block:: python
ReloadableBaseModel.reload_parent_schemas()
:returns: None.
Source code in src/disdantic/model.py
reload_schema(parents=True)
classmethod
¶
Forces a compilation rebuild of the local core schema.
This method triggers Pydantic's underlying model rebuilding process for the target model, forcing a compilation of its core schema. If parent cascading is requested and enabled globally, it also traverses the dependency tree to rebuild all models referencing this target model.
.. code-block:: python
ReloadableBaseModel.reload_schema(parents=True)
:param parents: Specifies whether schema updates should propagate to dependent parent models. :returns: None.
Source code in src/disdantic/model.py
Settings
¶
Bases: BaseSettings
Central configuration store and validation schema for the disdantic package.
This class serves as the single source of truth for runtime configurations, defining default options and loading overrides dynamically across modules. It integrates with Pydantic's BaseSettings to enforce type validation, coercion, and environment prefixing.
Example
.. code-block:: python
from disdantic.settings import Settings, get_settings
# Initialize a localized settings instance
settings = Settings(default_schema_discriminator="custom_type")
assert settings.default_schema_discriminator == "custom_type"
# Retrieve the global settings singleton instance
global_settings = get_settings()
print(global_settings.project_root)
Source code in src/disdantic/settings.py
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
model_config = SettingsConfigDict(arbitrary_types_allowed=True, extra='ignore', populate_by_name=True, validate_assignment=True, env_prefix='DISDANTIC__', cli_prefix='disdantic_', cli_parse_args=True, pyproject_toml_table_header=('tool', 'disdantic'))
class-attribute
¶
Configuration dictionary defining Pydantic Settings behavior options.
Controls environment variables parsing prefix, CLI integration arguments, pyproject.toml headers, and assignment validation rules.
__repr__()
¶
Generate a detailed string representation of the settings.
:returns: A detailed debug string representation of the settings.
__str__()
¶
Generate a concise string representation of the settings.
:returns: A human-readable string summary of the configuration state.
settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings)
classmethod
¶
Customize configuration loaders and define prioritize hierarchy.
This method overrides the default Pydantic source loading priorities to determine the resolving order of configuration options.
:param settings_cls: The settings class being constructed. :param init_settings: Settings passed directly to the class constructor. :param env_settings: Settings loaded from system environment variables. :param dotenv_settings: Settings loaded from active .env file streams. :param file_secret_settings: Settings loaded from secrets files paths. :returns: A tuple of settings sources ordered by loading priority.
Source code in src/disdantic/settings.py
SingletonMeta
¶
Bases: type
Thread-safe Singleton metaclass.
This metaclass intercepts class instantiation to enforce the singleton pattern, ensuring that subsequent calls to the class constructor return the same cached instance. It uses double-checked locking to guarantee thread safety during initialization without compromising read performance on subsequent retrievals.
Example
.. code-block:: python
from disdantic.singleton import SingletonMeta
class DatabaseConnection(metaclass=SingletonMeta):
def __init__(self, connection_string: str) -> None:
self.connection_string = connection_string
# Both variables reference the exact same instance
conn1 = DatabaseConnection("db://host1")
conn2 = DatabaseConnection("db://host2")
assert conn1 is conn2
Source code in src/disdantic/singleton.py
__call__(*args, **kwargs)
¶
Intercepts class instantiation to return the cached singleton instance.
If the instance does not already exist, it is created using double-checked locking to handle initialization race conditions.
:param args: Positional arguments passed to the class constructor. :param kwargs: Keyword arguments passed to the class constructor. :returns: The single, thread-safe cached instance of the class.
Source code in src/disdantic/singleton.py
clear_all_singletons()
classmethod
¶
Wipes all cached singleton instances across the application workspace.
This method is primarily designed for cleanup between test runs, ensuring that side effects from singleton states do not leak across test boundaries.
Source code in src/disdantic/singleton.py
clear_instances()
¶
Evicts the active single instance of the class from runtime tracking.
Calling this method allows a new instance of the class to be created on the next instantiation attempt.
Source code in src/disdantic/singleton.py
configure_logger(settings=None, **default_overrides)
¶
Configure the global Loguru logger based on settings.
This function initializes or updates the active logger handler. If no settings are provided, it loads settings from environment variables. It enables interception of standard library log statements and configures formatting, sinks, filtering, and queue options.
Example
.. code-block:: python
from disdantic.logging import LoggingSettings, configure_logger
configure_logger(
settings=LoggingSettings(level="INFO"),
clear_loggers=True
)
:param settings: Logging configurations, defaults to None (loads from environment). :param default_overrides: Parameter overrides merged into env settings if settings is None. :returns: None. :raises ImportError: Raised if OpenTelemetry formatting is enabled but the package is not installed.
Source code in src/disdantic/logging.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
get_registry_schema(registry_class, *, format='json')
¶
Generates the schema for the specified registry base class.
Example
.. code-block:: python
from disdantic.schema import get_registry_schema
from myapp.registry import MyRegistry
# Generate OpenAPI schema for the registry
schema = get_registry_schema(MyRegistry, format="openapi")
:param registry_class: The registry base class subclassing PydanticClassRegistryMixin. :param format: The output format, either 'json' or 'openapi'. :raises TypeError: If the registry_class is not a subclass of PydanticClassRegistryMixin. :returns: A dictionary representing the generated schema.
Source code in src/disdantic/schema.py
get_settings()
¶
Retrieve the global Settings singleton instance.
Uses double-checked locking to resolve initialization race conditions in multi-threaded applications.
Example
.. code-block:: python
from disdantic.settings import get_settings
settings = get_settings()
print(settings.project_root)
:returns: The global Settings singleton instance.
Source code in src/disdantic/settings.py
reset_settings()
¶
Reset the global Settings singleton instance to None.
Forces a complete reload and re-validation of settings on the next invocation of get_settings().
Example
.. code-block:: python
from disdantic.settings import reset_settings
# Evicts active settings from memory
reset_settings()
:returns: None
Source code in src/disdantic/settings.py
verify_registries(settings=None)
¶
Scan configured packages, discover registries, and verify compilation.
Examples:
.. code-block:: python
from disdantic.diagnose import verify_registries
report = verify_registries()
if not report.is_healthy:
print(f"Diagnostics failed. Errors: {report.import_errors}")
:param settings: Optional settings configuration instance to customize packages and ignore rules. :returns: The aggregated health diagnostics report.