API Reference¶
This page exposes the main public API modules.
Package Exports¶
monkay
¶
InGlobalsDict
¶
Bases: Exception
Source code in monkay/base.py
UnsetError
¶
Bases: RuntimeError
Source code in monkay/base.py
Cage
¶
Bases: Generic[T]
A container class that manages a value with context-aware modifications and synchronization.
Source code in monkay/cages.py
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 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 370 371 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 | |
monkay_context_var
instance-attribute
¶
A context variable that stores the current value and update timestamp within a specific context. This allows for context-specific modifications and retrieval of the value.
monkay_deep_copy
instance-attribute
¶
A boolean indicating whether deep copies should be used when modifying the value. If True, modifications will create deep copies of the original value to avoid unintended side effects.
monkay_use_wrapper_for_reads
instance-attribute
¶
A boolean indicating whether a wrapper should be used for read operations. If True, read operations will be wrapped in a context manager to ensure consistency.
monkay_update_fn
instance-attribute
¶
An optional function that defines how to update the value when modifications are made. This function takes the current value and the new value as input and returns the updated value.
monkay_name
instance-attribute
¶
A name associated with the Cage instance, used for identification and debugging purposes.
monkay_original
instance-attribute
¶
The original value stored in the Cage instance. This attribute holds the initial value that is managed by the Cage.
monkay_original_last_update
instance-attribute
¶
A timestamp indicating the last time the original value was updated. This timestamp is used to track changes and ensure consistency.
monkay_original_last_update_lock
instance-attribute
¶
An optional lock used to synchronize updates to the original value. This lock prevents race conditions when multiple threads or processes try to update the value concurrently.
monkay_original_wrapper
instance-attribute
¶
A context manager used to wrap access to the original value, ensuring consistency and synchronization. This wrapper provides a controlled environment for read and write operations on the original value.
monkay_forward
classmethod
¶
Creates a wrapper function that forwards method calls to the wrapped object.
This class method generates a wrapper function that intercepts method calls to the Cage instance and forwards them to the wrapped object, ensuring that the object is updated or copied as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_type
|
type
|
The type of the wrapped object. |
required |
name
|
str
|
The name of the method to forward. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A wrapper function that forwards method calls. |
Source code in monkay/cages.py
monkay_refresh_copy
¶
monkay_refresh_copy(*, obj=Undefined, use_wrapper=None, _monkay_dict=None)
Refreshes the context variable with a copy of the original object.
This method updates the context variable with a fresh copy of the original object, optionally using a wrapper and handling deep or shallow copies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
T | type[Undefined]
|
An optional object to use instead of creating a copy. |
Undefined
|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The refreshed object. |
Source code in monkay/cages.py
monkay_conditional_update_copy
¶
Retrieves a context-aware copy of the original object, updating it if necessary.
This method retrieves a copy of the original object, updating it based on context and update functions. It checks if the context variable is set and if the original object has been updated, and applies the update function if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The context-aware copy of the object. |
Source code in monkay/cages.py
monkay_proxied
¶
Returns a proxied version of the object, ensuring context-aware updates.
This method returns a context-aware copy of the object, optionally using a wrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The proxied object. |
Source code in monkay/cages.py
monkay_with_override
¶
Temporarily overrides the context variable with a new value within a context.
This context manager temporarily sets the context variable to a new value and yields it. After the context exits, the original context variable is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
allow_value_update
|
bool
|
If True, allows the value to be updated by the update function. If False, the value will not be updated. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The new value. |
Source code in monkay/cages.py
monkay_with_original
¶
Temporarily accesses the original value within a context, optionally updating it.
This context manager yields the original value, optionally using a wrapper and updating the last update timestamp after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool
|
If True, uses the original wrapper when accessing the original value. |
True
|
update_after
|
bool
|
If True, updates the last update timestamp after the context exits. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The original value. |
Source code in monkay/cages.py
monkay_set
¶
Sets the context variable to a new value and returns a token.
This method sets the context variable to a new value and returns a token that can be used to reset the context variable to its previous value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
Returns:
| Type | Description |
|---|---|
Token
|
A token that can be used to reset the context variable. |
Source code in monkay/cages.py
monkay_get
¶
Retrieves the current value of the context variable, or a default value if it's not set.
This method retrieves the current value of the context variable. If the context variable is not set, it returns the original value or a default value if provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
T | DEFAULT | None
|
The default value to return if the context variable is not set. |
None
|
Returns:
| Type | Description |
|---|---|
T | DEFAULT | None
|
The current value of the context variable, the original value, or the default value. |
Source code in monkay/cages.py
monkay_reset
¶
Resets the context variable to its previous value using a token.
This method resets the context variable to its previous value using a token returned by monkay_set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Token
|
The token returned by |
required |
Source code in monkay/cages.py
TransparentCage
¶
Bases: Cage
A transparent Cage subclass that exposes context variable attributes directly.
This subclass of Cage allows direct access to context variable attributes (e.g., 'get', 'set', 'reset') without requiring the 'monkay_' prefix. It provides a more transparent interface for interacting with context-aware values.
Source code in monkay/cages.py
monkay_context_var
instance-attribute
¶
A context variable that stores the current value and update timestamp within a specific context. This allows for context-specific modifications and retrieval of the value.
monkay_deep_copy
instance-attribute
¶
A boolean indicating whether deep copies should be used when modifying the value. If True, modifications will create deep copies of the original value to avoid unintended side effects.
monkay_use_wrapper_for_reads
instance-attribute
¶
A boolean indicating whether a wrapper should be used for read operations. If True, read operations will be wrapped in a context manager to ensure consistency.
monkay_update_fn
instance-attribute
¶
An optional function that defines how to update the value when modifications are made. This function takes the current value and the new value as input and returns the updated value.
monkay_name
instance-attribute
¶
A name associated with the Cage instance, used for identification and debugging purposes.
monkay_original
instance-attribute
¶
The original value stored in the Cage instance. This attribute holds the initial value that is managed by the Cage.
monkay_original_last_update
instance-attribute
¶
A timestamp indicating the last time the original value was updated. This timestamp is used to track changes and ensure consistency.
monkay_original_last_update_lock
instance-attribute
¶
An optional lock used to synchronize updates to the original value. This lock prevents race conditions when multiple threads or processes try to update the value concurrently.
monkay_original_wrapper
instance-attribute
¶
A context manager used to wrap access to the original value, ensuring consistency and synchronization. This wrapper provides a controlled environment for read and write operations on the original value.
monkay_forward
classmethod
¶
Creates a wrapper function that forwards method calls to the wrapped object.
This class method generates a wrapper function that intercepts method calls to the Cage instance and forwards them to the wrapped object, ensuring that the object is updated or copied as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_type
|
type
|
The type of the wrapped object. |
required |
name
|
str
|
The name of the method to forward. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A wrapper function that forwards method calls. |
Source code in monkay/cages.py
monkay_refresh_copy
¶
monkay_refresh_copy(*, obj=Undefined, use_wrapper=None, _monkay_dict=None)
Refreshes the context variable with a copy of the original object.
This method updates the context variable with a fresh copy of the original object, optionally using a wrapper and handling deep or shallow copies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
T | type[Undefined]
|
An optional object to use instead of creating a copy. |
Undefined
|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The refreshed object. |
Source code in monkay/cages.py
monkay_conditional_update_copy
¶
Retrieves a context-aware copy of the original object, updating it if necessary.
This method retrieves a copy of the original object, updating it based on context and update functions. It checks if the context variable is set and if the original object has been updated, and applies the update function if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The context-aware copy of the object. |
Source code in monkay/cages.py
monkay_proxied
¶
Returns a proxied version of the object, ensuring context-aware updates.
This method returns a context-aware copy of the object, optionally using a wrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The proxied object. |
Source code in monkay/cages.py
monkay_with_override
¶
Temporarily overrides the context variable with a new value within a context.
This context manager temporarily sets the context variable to a new value and yields it. After the context exits, the original context variable is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
allow_value_update
|
bool
|
If True, allows the value to be updated by the update function. If False, the value will not be updated. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The new value. |
Source code in monkay/cages.py
monkay_with_original
¶
Temporarily accesses the original value within a context, optionally updating it.
This context manager yields the original value, optionally using a wrapper and updating the last update timestamp after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool
|
If True, uses the original wrapper when accessing the original value. |
True
|
update_after
|
bool
|
If True, updates the last update timestamp after the context exits. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The original value. |
Source code in monkay/cages.py
monkay_set
¶
Sets the context variable to a new value and returns a token.
This method sets the context variable to a new value and returns a token that can be used to reset the context variable to its previous value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
Returns:
| Type | Description |
|---|---|
Token
|
A token that can be used to reset the context variable. |
Source code in monkay/cages.py
monkay_get
¶
Retrieves the current value of the context variable, or a default value if it's not set.
This method retrieves the current value of the context variable. If the context variable is not set, it returns the original value or a default value if provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
T | DEFAULT | None
|
The default value to return if the context variable is not set. |
None
|
Returns:
| Type | Description |
|---|---|
T | DEFAULT | None
|
The current value of the context variable, the original value, or the default value. |
Source code in monkay/cages.py
monkay_reset
¶
Resets the context variable to its previous value using a token.
This method resets the context variable to its previous value using a token returned by monkay_set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Token
|
The token returned by |
required |
Source code in monkay/cages.py
Monkay
¶
Bases: MonkayInstance[INSTANCE, SETTINGS], MonkaySettings[SETTINGS], MonkayExports, Generic[INSTANCE, SETTINGS]
A comprehensive class that combines instance, settings, and export management for a module.
This class provides a unified interface for managing module instances, settings, and exports. It integrates lazy imports, deprecated imports, settings loading, and instance management.
Source code in monkay/core.py
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 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 370 371 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 | |
getter
class-attribute
instance-attribute
¶
The getter function used for attribute access, initialized with lazy import logic. This function handles both regular attribute access and the resolution of lazy imports.
dir_fn
class-attribute
instance-attribute
¶
The directory listing function, enhanced to include lazy imports. This function is used to generate the list of attributes available in the module.
settings_evaluated
property
writable
¶
Checks if the settings have been evaluated and loaded.
This property returns a boolean indicating whether the settings have been evaluated. It checks both the global settings evaluation flag and the context-specific flag.
Returns:
| Type | Description |
|---|---|
bool
|
True if the settings have been evaluated, False otherwise. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for settings. |
instance
property
¶
Retrieves the current instance managed by Monkay.
This property returns the instance associated with the Monkay object. It first checks if a context-specific
instance is set via _instance_var. If not, it returns the default instance _instance.
Returns:
| Type | Description |
|---|---|
INSTANCE | None
|
The current instance, or None if no instance is set. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for instances. |
post_add_lazy_import_hook
instance-attribute
¶
find_missing
¶
find_missing(*, all_var=True, search_pathes=None, ignore_deprecated_import_errors=False, require_search_path_all_var=True)
Debug method to check for missing imports and inconsistencies in exports.
This method performs a comprehensive check for missing attributes, imports,
and inconsistencies in the module's exports, including lazy and deprecated imports.
It compares the defined exports with the module's __all__ variable and optional
search paths to identify potential issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_var
|
bool | Collection[str]
|
If True, checks against the module's |
True
|
search_pathes
|
None | Collection[str]
|
Optional list of module paths to search for additional exports. |
None
|
ignore_deprecated_import_errors
|
bool
|
If True, ignores import errors for deprecated lazy imports. |
False
|
require_search_path_all_var
|
bool
|
If True, requires |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, set[Literal['not_in_all_var', 'missing_attr', 'missing_all_var', 'import', 'shadowed', 'search_path_extra', 'search_path_import']]]
|
A dictionary where keys are names of missing or inconsistent items, |
dict[str, set[Literal['not_in_all_var', 'missing_attr', 'missing_all_var', 'import', 'shadowed', 'search_path_extra', 'search_path_import']]]
|
and values are sets of strings indicating the types of issues. |
Issue types
- "not_in_all_var": Export is defined but not in
__all__. - "missing_attr": Attribute is missing from the module or a searched module.
- "missing_all_var":
__all__is missing from the module or a searched module. - "import": Import error occurred while resolving a lazy or deprecated import.
- "shadowed": Attribute is shadowed by a real variable in the module's globals.
- "search_path_extra": Export from a search path is not found in the module's exports.
- "search_path_import": Import error occurred while importing a search path.
Source code in monkay/_monkay_exports.py
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 | |
add_lazy_import
¶
Adds a lazy import to the module.
This method adds a lazy import, which is resolved only when the attribute is accessed. This can improve module loading performance by deferring imports.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the lazy import. |
required |
value
|
str | Callable[[], Any]
|
The import path as a string or a callable that returns the imported object. |
required |
no_hooks
|
bool
|
If True, skips the pre and post add hooks. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name is already a lazy or deprecated lazy import. |
Source code in monkay/_monkay_exports.py
add_deprecated_lazy_import
¶
Adds a deprecated lazy import to the module.
This method adds a lazy import that is marked as deprecated. When accessed, it will issue a deprecation warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the deprecated import. |
required |
value
|
DeprecatedImport
|
A dictionary containing details about the deprecation, including the import path. |
required |
no_hooks
|
bool
|
If True, skips the pre and post add hooks. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name is already a lazy or deprecated lazy import. |
Source code in monkay/_monkay_exports.py
sorted_exports
¶
Returns a sorted list of module exports, categorized and sorted as specified.
This method generates a list of SortedExportsEntry objects, which represent the module's exports.
It categorizes exports as "lazy_import", "deprecated_lazy_import", or "other", and sorts them
based on the specified criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_var
|
Collection[str] | None
|
An optional collection of export names. If None, uses the module's |
None
|
separate_by_category
|
bool
|
If True, sorts exports by category first, then by the specified |
True
|
sort_by
|
Literal['export_name', 'path']
|
The attribute to sort by, either "export_name" or "path". |
'path'
|
Returns:
| Type | Description |
|---|---|
list[SortedExportsEntry]
|
A list of |
Source code in monkay/_monkay_exports.py
module_dir_fn
¶
Generates a directory listing for the module, including lazy and deprecated imports.
This method combines the module's __all__ variable, lazy imports, deprecated lazy imports,
and optionally the results of a chained directory listing function to create a comprehensive
list of attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chained_dir_fn
|
Callable[[], list[str]] | None
|
An optional function that returns a list of attribute names, used to extend the directory listing. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of attribute names representing the module's directory. |
Source code in monkay/_monkay_exports.py
module_getter
¶
module_getter(key, *, chained_getter=_stub_previous_getattr, no_warn_deprecated=False, check_globals_dict=False)
Module Getter which handles lazy imports.
This method acts as a custom attribute getter for the module, handling lazy imports and deprecated attributes. It first checks if the attribute exists in the module's globals dictionary. If not, it checks for lazy or deprecated lazy imports. If found, it resolves and returns the imported object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The name of the attribute to retrieve. |
required |
chained_getter
|
Callable[[str], Any]
|
A fallback getter function to call if the attribute is not found in lazy imports. |
_stub_previous_getattr
|
no_warn_deprecated
|
bool
|
If True, suppresses deprecation warnings for deprecated attributes. |
False
|
check_globals_dict
|
bool | Literal['fail']
|
If True, checks the module's globals dictionary first. If "fail", raises InGlobalsDict if found. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The retrieved attribute value. |
Raises:
| Type | Description |
|---|---|
InglobalsDict
|
If |
DeprecationWarning
|
If a deprecated attribute is accessed and |
Source code in monkay/_monkay_exports.py
update_all_var
¶
Updates the __all__ variable to include lazy and deprecated lazy imports.
This method ensures that all names defined as lazy or deprecated lazy imports
are included in the module's __all__ variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_var
|
Collection[str]
|
The current |
required |
Returns:
| Type | Description |
|---|---|
list[str] | set[str]
|
The updated |
Source code in monkay/_monkay_exports.py
with_settings
¶
Temporarily sets and yields new settings for the Monkay instance within a context.
This context manager allows temporarily overriding the settings associated with the Monkay instance. It yields the provided settings and then restores the original settings after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
SETTINGS_DEFINITION_TYPE[SETTINGS] | None | Literal[False]
|
The new settings to use within the context, or None to temporarily use the real settings. Use False, "" to disable settings access temporarily |
required |
evaluate_settings_with
|
EvaluateSettingsParameters | None
|
Evaluate settings with the parameters provided. |
None
|
Yields:
| Type | Description |
|---|---|
Generator[SETTINGS_DEFINITION_TYPE[SETTINGS] | Literal[False] | None]
|
The provided settings. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for settings. |
Source code in monkay/_monkay_settings.py
apply_extensions
¶
Applies registered extensions to the Monkay instance.
This method iterates through the registered extensions, applies them in the specified order, and manages the application process to prevent recursive or concurrent application issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_overwrite
|
bool
|
If True, uses the extensions from the |
True
|
Raises: AssertionError: If Monkay is not enabled for extensions. RuntimeError: If another extension application process is already active in the same context.
Source code in monkay/_monkay_extensions.py
ensure_extension
¶
Ensures that a specific extension is applied to the Monkay instance.
This method checks if the given extension (either by name or instance) is already applied. If not, it applies the extension, preventing recursive application issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_or_extension
|
str | ExtensionProtocol[INSTANCE, SETTINGS]
|
The name of the extension or an instance of the extension. |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for extensions or if applying extensions is not active. |
RuntimeError
|
If the provided extension does not implement the ExtensionProtocol, or if the extension does not exist. |
Source code in monkay/_monkay_extensions.py
add_extension
¶
Register an extension on the active extension registry.
The method accepts an already-instantiated extension, an extension class, or a zero-argument factory. The input is normalized to an extension instance and then inserted into the currently active registry (context override or base registry).
Conflict handling is explicit and validated at runtime:
"error" raises, "keep" preserves the existing extension,
and "replace" overwrites the existing one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extension
|
ExtensionProtocol[INSTANCE, SETTINGS] | type[ExtensionProtocol[INSTANCE, SETTINGS]] | Callable[[], ExtensionProtocol[INSTANCE, SETTINGS]]
|
Extension instance, extension class, or factory callable. |
required |
use_overwrite
|
bool
|
Use the active |
True
|
on_conflict
|
Literal['error', 'keep', 'replace']
|
Strategy used when an extension with the same name is
already present. Supported values are |
'error'
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If extensions support is not enabled. |
ValueError
|
If |
KeyError
|
If the extension name already exists and |
Examples:
>>> monkay.add_extension(MyExtension())
>>> monkay.add_extension(MyExtension, on_conflict="replace")
Notes
on_conflict is validated even when no name collision happens.
This keeps behavior deterministic across input data sets.
Source code in monkay/_monkay_extensions.py
with_extensions
¶
Temporarily sets and yields a new set of extensions for the Monkay instance.
This method allows temporarily overriding the registered extensions within a context. It yields the provided extensions (or None to temporarily use the real extensions), and then restores the original extensions after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extensions
|
dict[str, ExtensionProtocol[INSTANCE, SETTINGS]] | None
|
The new set of extensions to use within the context, or None to temporarily use the real extensions. |
required |
apply_extensions
|
bool
|
If True, applies the temporary extensions immediately after setting them. |
False
|
Yields:
| Type | Description |
|---|---|
Generator[dict[str, ExtensionProtocol[INSTANCE, SETTINGS]] | None]
|
The provided extensions (or None). |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for extensions. |
Source code in monkay/_monkay_extensions.py
set_instance
¶
Sets the instance managed by Monkay and optionally applies extensions.
This method updates the instance associated with the Monkay object. It also allows applying extensions immediately after setting the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
INSTANCE | None
|
The new instance to set, or None to unset the instance. |
required |
apply_extensions
|
bool
|
If True, applies the registered extensions after setting the instance. |
True
|
use_extensions_overwrite
|
bool
|
If True, uses the extensions from the |
True
|
Returns:
| Type | Description |
|---|---|
INSTANCE | None
|
The set instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for instances. |
RuntimeError
|
If another extension application process is already active in the same context. |
Source code in monkay/_monkay_instance.py
with_instance
¶
Temporarily sets and yields a new instance for the Monkay object within a context.
This context manager allows temporarily overriding the instance associated with the Monkay object. It yields the provided instance and then restores the original instance after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
INSTANCE | None
|
The new instance to use within the context, or None to temporarily unset the instance. |
required |
apply_extensions
|
bool
|
If True, applies the registered extensions after setting the instance. |
False
|
use_extensions_overwrite
|
bool
|
If True, uses the extensions from the |
True
|
Yields:
| Type | Description |
|---|---|
Generator[INSTANCE | None]
|
The provided instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for instances. |
RuntimeError
|
If another extension application process is already active in the same context. |
Source code in monkay/_monkay_instance.py
clear_caches
¶
Clears the settings and import caches.
This method clears the cached settings and/or import objects, forcing them to be reloaded on next access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings_cache
|
bool
|
If True, clears the settings cache. |
True
|
import_cache
|
bool
|
If True, clears the import cache. |
True
|
Source code in monkay/core.py
evaluate_preloads
¶
Evaluates preload modules or functions specified in settings.
This method delegates to the evaluate_preloads function, using the Monkay instance's
package if no package is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preloads
|
Iterable[str]
|
An iterable of preload paths, in the format "module" or "module:function". |
required |
ignore_import_errors
|
bool
|
If True, ignores import errors and continues processing. |
True
|
package
|
str | None
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if all preloads were successfully evaluated, False otherwise. |
Source code in monkay/core.py
evaluate_settings
¶
evaluate_settings(*, on_conflict='error', ignore_import_errors=False, ignore_preload_import_errors=True, onetime=True)
Evaluate settings-driven preloads and extension registrations.
This method is the main runtime entry point for applying configuration
declared in settings_preloads_name and settings_extensions_name.
It can be called repeatedly; with onetime=True it becomes idempotent
per context once evaluation succeeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_conflict
|
Literal['error', 'keep', 'replace']
|
Conflict policy applied while registering extensions from
settings. Supported values are |
'error'
|
ignore_import_errors
|
bool
|
Return |
False
|
ignore_preload_import_errors
|
bool
|
Continue when a settings preload import fails. |
True
|
onetime
|
bool
|
Skip re-evaluation if settings were already evaluated in the active context. |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
bool
|
failed with an import/unset error. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Exception
|
Any exception raised while loading settings or applying preloads/extensions when not suppressed. |
Examples:
>>> monkay.evaluate_settings()
True
>>> monkay.evaluate_settings(on_conflict="replace", onetime=False)
True
Notes
When neither settings_preloads_name nor settings_extensions_name
is configured, this method marks settings as evaluated without touching
monkay.settings.
Source code in monkay/core.py
evaluate_settings_once
¶
Evaluates settings preloads and extensions once. (Deprecated)
This method is deprecated and now equivalent to evaluate_settings(onetime=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_conflict
|
Literal['error', 'keep', 'replace']
|
Specifies how to handle conflicts when adding extensions. |
'error'
|
ignore_import_errors
|
bool
|
If True, ignores settings import errors. |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
True if settings were successfully evaluated, False otherwise. |
Source code in monkay/core.py
with_full_overwrite
¶
with_full_overwrite(*, extensions=Undefined, settings=Undefined, instance=Undefined, apply_extensions=False, evaluate_settings_with=None)
Apply all overwrites in the correct order. Useful for testing or sub-environments
Source code in monkay/core.py
PRE_ADD_LAZY_IMPORT_HOOK
¶
Bases: Protocol
A protocol defining the signature for a hook that modifies lazy import definitions before they are added.
This protocol specifies the expected signature for a hook function that can be used to modify lazy import definitions before they are added to the module. It supports both regular lazy imports and deprecated lazy imports.
Source code in monkay/types.py
DeprecatedImport
¶
Bases: TypedDict
Represents a deprecated import with optional deprecation details.
This class defines the structure for deprecated imports, including the import path, reason for deprecation, and a replacement attribute.
Source code in monkay/types.py
absolutify_import
¶
Converts a relative import path to an absolute import path.
This function takes an import path and a package name and converts the relative import path to an absolute path by prepending the package name and adjusting for relative levels (e.g., "..module").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
import_path
|
str
|
The import path to absolutify. |
required |
package
|
str | None
|
The package name to use as a base for relative imports. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The absolute import path. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the import path is invalid or tries to cross parent boundaries. |
Source code in monkay/base.py
get_value_from_settings
¶
Retrieves a value from a settings object, supporting both attribute and dictionary access.
This function attempts to retrieve a value from a settings object. It first tries to access the value as an attribute. If that fails, it tries to access the value as a dictionary key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
Any
|
The settings object to retrieve the value from. |
required |
name
|
str
|
The name of the attribute or key to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The retrieved value. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If the name is not found as an attribute and the settings object does not support dictionary access. |
KeyError
|
If the name is not found as a key in the settings object and attribute access also fails. |
Source code in monkay/base.py
load
¶
Dynamically loads an object from a module given its path.
This function takes a string representing the path to an object within a module and dynamically imports the module and retrieves the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the object, in the format "module:object" or "module.object". |
required |
allow_splits
|
str
|
A string specifying the allowed separators for module and object names. Defaults to ":." allowing both ":" and "." as separators. |
':.'
|
package
|
None | str
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The loaded object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path is invalid or cannot be parsed. |
ImportError
|
If the module cannot be imported. |
Source code in monkay/base.py
load_any
¶
Dynamically loads any of the specified attributes from a module.
This function takes a module path and a collection of attribute names. It attempts to import the module and retrieve each attribute in the given order. If any of the attributes are found, it returns the first one found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the module. |
required |
attrs
|
Collection[str]
|
A collection of attribute names to search for. |
required |
non_first_deprecated
|
bool
|
If True, issues deprecation warnings for all found attributes except the first one. |
False
|
package
|
None | str
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
Any | None
|
The first found attribute, or None if none of the attributes are found. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the module cannot be imported or none of the attributes are found. |
DeprecationWarning
|
If |
Source code in monkay/base.py
Core¶
monkay.core
¶
Monkay
¶
Bases: MonkayInstance[INSTANCE, SETTINGS], MonkaySettings[SETTINGS], MonkayExports, Generic[INSTANCE, SETTINGS]
A comprehensive class that combines instance, settings, and export management for a module.
This class provides a unified interface for managing module instances, settings, and exports. It integrates lazy imports, deprecated imports, settings loading, and instance management.
Source code in monkay/core.py
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 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 370 371 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 | |
post_add_lazy_import_hook
instance-attribute
¶
getter
class-attribute
instance-attribute
¶
The getter function used for attribute access, initialized with lazy import logic. This function handles both regular attribute access and the resolution of lazy imports.
dir_fn
class-attribute
instance-attribute
¶
The directory listing function, enhanced to include lazy imports. This function is used to generate the list of attributes available in the module.
settings_evaluated
property
writable
¶
Checks if the settings have been evaluated and loaded.
This property returns a boolean indicating whether the settings have been evaluated. It checks both the global settings evaluation flag and the context-specific flag.
Returns:
| Type | Description |
|---|---|
bool
|
True if the settings have been evaluated, False otherwise. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for settings. |
instance
property
¶
Retrieves the current instance managed by Monkay.
This property returns the instance associated with the Monkay object. It first checks if a context-specific
instance is set via _instance_var. If not, it returns the default instance _instance.
Returns:
| Type | Description |
|---|---|
INSTANCE | None
|
The current instance, or None if no instance is set. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for instances. |
clear_caches
¶
Clears the settings and import caches.
This method clears the cached settings and/or import objects, forcing them to be reloaded on next access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings_cache
|
bool
|
If True, clears the settings cache. |
True
|
import_cache
|
bool
|
If True, clears the import cache. |
True
|
Source code in monkay/core.py
evaluate_preloads
¶
Evaluates preload modules or functions specified in settings.
This method delegates to the evaluate_preloads function, using the Monkay instance's
package if no package is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preloads
|
Iterable[str]
|
An iterable of preload paths, in the format "module" or "module:function". |
required |
ignore_import_errors
|
bool
|
If True, ignores import errors and continues processing. |
True
|
package
|
str | None
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if all preloads were successfully evaluated, False otherwise. |
Source code in monkay/core.py
evaluate_settings
¶
evaluate_settings(*, on_conflict='error', ignore_import_errors=False, ignore_preload_import_errors=True, onetime=True)
Evaluate settings-driven preloads and extension registrations.
This method is the main runtime entry point for applying configuration
declared in settings_preloads_name and settings_extensions_name.
It can be called repeatedly; with onetime=True it becomes idempotent
per context once evaluation succeeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_conflict
|
Literal['error', 'keep', 'replace']
|
Conflict policy applied while registering extensions from
settings. Supported values are |
'error'
|
ignore_import_errors
|
bool
|
Return |
False
|
ignore_preload_import_errors
|
bool
|
Continue when a settings preload import fails. |
True
|
onetime
|
bool
|
Skip re-evaluation if settings were already evaluated in the active context. |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
bool
|
failed with an import/unset error. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Exception
|
Any exception raised while loading settings or applying preloads/extensions when not suppressed. |
Examples:
>>> monkay.evaluate_settings()
True
>>> monkay.evaluate_settings(on_conflict="replace", onetime=False)
True
Notes
When neither settings_preloads_name nor settings_extensions_name
is configured, this method marks settings as evaluated without touching
monkay.settings.
Source code in monkay/core.py
evaluate_settings_once
¶
Evaluates settings preloads and extensions once. (Deprecated)
This method is deprecated and now equivalent to evaluate_settings(onetime=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_conflict
|
Literal['error', 'keep', 'replace']
|
Specifies how to handle conflicts when adding extensions. |
'error'
|
ignore_import_errors
|
bool
|
If True, ignores settings import errors. |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
True if settings were successfully evaluated, False otherwise. |
Source code in monkay/core.py
with_full_overwrite
¶
with_full_overwrite(*, extensions=Undefined, settings=Undefined, instance=Undefined, apply_extensions=False, evaluate_settings_with=None)
Apply all overwrites in the correct order. Useful for testing or sub-environments
Source code in monkay/core.py
find_missing
¶
find_missing(*, all_var=True, search_pathes=None, ignore_deprecated_import_errors=False, require_search_path_all_var=True)
Debug method to check for missing imports and inconsistencies in exports.
This method performs a comprehensive check for missing attributes, imports,
and inconsistencies in the module's exports, including lazy and deprecated imports.
It compares the defined exports with the module's __all__ variable and optional
search paths to identify potential issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_var
|
bool | Collection[str]
|
If True, checks against the module's |
True
|
search_pathes
|
None | Collection[str]
|
Optional list of module paths to search for additional exports. |
None
|
ignore_deprecated_import_errors
|
bool
|
If True, ignores import errors for deprecated lazy imports. |
False
|
require_search_path_all_var
|
bool
|
If True, requires |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, set[Literal['not_in_all_var', 'missing_attr', 'missing_all_var', 'import', 'shadowed', 'search_path_extra', 'search_path_import']]]
|
A dictionary where keys are names of missing or inconsistent items, |
dict[str, set[Literal['not_in_all_var', 'missing_attr', 'missing_all_var', 'import', 'shadowed', 'search_path_extra', 'search_path_import']]]
|
and values are sets of strings indicating the types of issues. |
Issue types
- "not_in_all_var": Export is defined but not in
__all__. - "missing_attr": Attribute is missing from the module or a searched module.
- "missing_all_var":
__all__is missing from the module or a searched module. - "import": Import error occurred while resolving a lazy or deprecated import.
- "shadowed": Attribute is shadowed by a real variable in the module's globals.
- "search_path_extra": Export from a search path is not found in the module's exports.
- "search_path_import": Import error occurred while importing a search path.
Source code in monkay/_monkay_exports.py
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 | |
add_lazy_import
¶
Adds a lazy import to the module.
This method adds a lazy import, which is resolved only when the attribute is accessed. This can improve module loading performance by deferring imports.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the lazy import. |
required |
value
|
str | Callable[[], Any]
|
The import path as a string or a callable that returns the imported object. |
required |
no_hooks
|
bool
|
If True, skips the pre and post add hooks. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name is already a lazy or deprecated lazy import. |
Source code in monkay/_monkay_exports.py
add_deprecated_lazy_import
¶
Adds a deprecated lazy import to the module.
This method adds a lazy import that is marked as deprecated. When accessed, it will issue a deprecation warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the deprecated import. |
required |
value
|
DeprecatedImport
|
A dictionary containing details about the deprecation, including the import path. |
required |
no_hooks
|
bool
|
If True, skips the pre and post add hooks. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name is already a lazy or deprecated lazy import. |
Source code in monkay/_monkay_exports.py
sorted_exports
¶
Returns a sorted list of module exports, categorized and sorted as specified.
This method generates a list of SortedExportsEntry objects, which represent the module's exports.
It categorizes exports as "lazy_import", "deprecated_lazy_import", or "other", and sorts them
based on the specified criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_var
|
Collection[str] | None
|
An optional collection of export names. If None, uses the module's |
None
|
separate_by_category
|
bool
|
If True, sorts exports by category first, then by the specified |
True
|
sort_by
|
Literal['export_name', 'path']
|
The attribute to sort by, either "export_name" or "path". |
'path'
|
Returns:
| Type | Description |
|---|---|
list[SortedExportsEntry]
|
A list of |
Source code in monkay/_monkay_exports.py
module_dir_fn
¶
Generates a directory listing for the module, including lazy and deprecated imports.
This method combines the module's __all__ variable, lazy imports, deprecated lazy imports,
and optionally the results of a chained directory listing function to create a comprehensive
list of attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chained_dir_fn
|
Callable[[], list[str]] | None
|
An optional function that returns a list of attribute names, used to extend the directory listing. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of attribute names representing the module's directory. |
Source code in monkay/_monkay_exports.py
module_getter
¶
module_getter(key, *, chained_getter=_stub_previous_getattr, no_warn_deprecated=False, check_globals_dict=False)
Module Getter which handles lazy imports.
This method acts as a custom attribute getter for the module, handling lazy imports and deprecated attributes. It first checks if the attribute exists in the module's globals dictionary. If not, it checks for lazy or deprecated lazy imports. If found, it resolves and returns the imported object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The name of the attribute to retrieve. |
required |
chained_getter
|
Callable[[str], Any]
|
A fallback getter function to call if the attribute is not found in lazy imports. |
_stub_previous_getattr
|
no_warn_deprecated
|
bool
|
If True, suppresses deprecation warnings for deprecated attributes. |
False
|
check_globals_dict
|
bool | Literal['fail']
|
If True, checks the module's globals dictionary first. If "fail", raises InGlobalsDict if found. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The retrieved attribute value. |
Raises:
| Type | Description |
|---|---|
InglobalsDict
|
If |
DeprecationWarning
|
If a deprecated attribute is accessed and |
Source code in monkay/_monkay_exports.py
update_all_var
¶
Updates the __all__ variable to include lazy and deprecated lazy imports.
This method ensures that all names defined as lazy or deprecated lazy imports
are included in the module's __all__ variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_var
|
Collection[str]
|
The current |
required |
Returns:
| Type | Description |
|---|---|
list[str] | set[str]
|
The updated |
Source code in monkay/_monkay_exports.py
with_settings
¶
Temporarily sets and yields new settings for the Monkay instance within a context.
This context manager allows temporarily overriding the settings associated with the Monkay instance. It yields the provided settings and then restores the original settings after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
SETTINGS_DEFINITION_TYPE[SETTINGS] | None | Literal[False]
|
The new settings to use within the context, or None to temporarily use the real settings. Use False, "" to disable settings access temporarily |
required |
evaluate_settings_with
|
EvaluateSettingsParameters | None
|
Evaluate settings with the parameters provided. |
None
|
Yields:
| Type | Description |
|---|---|
Generator[SETTINGS_DEFINITION_TYPE[SETTINGS] | Literal[False] | None]
|
The provided settings. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for settings. |
Source code in monkay/_monkay_settings.py
apply_extensions
¶
Applies registered extensions to the Monkay instance.
This method iterates through the registered extensions, applies them in the specified order, and manages the application process to prevent recursive or concurrent application issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_overwrite
|
bool
|
If True, uses the extensions from the |
True
|
Raises: AssertionError: If Monkay is not enabled for extensions. RuntimeError: If another extension application process is already active in the same context.
Source code in monkay/_monkay_extensions.py
ensure_extension
¶
Ensures that a specific extension is applied to the Monkay instance.
This method checks if the given extension (either by name or instance) is already applied. If not, it applies the extension, preventing recursive application issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_or_extension
|
str | ExtensionProtocol[INSTANCE, SETTINGS]
|
The name of the extension or an instance of the extension. |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for extensions or if applying extensions is not active. |
RuntimeError
|
If the provided extension does not implement the ExtensionProtocol, or if the extension does not exist. |
Source code in monkay/_monkay_extensions.py
add_extension
¶
Register an extension on the active extension registry.
The method accepts an already-instantiated extension, an extension class, or a zero-argument factory. The input is normalized to an extension instance and then inserted into the currently active registry (context override or base registry).
Conflict handling is explicit and validated at runtime:
"error" raises, "keep" preserves the existing extension,
and "replace" overwrites the existing one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extension
|
ExtensionProtocol[INSTANCE, SETTINGS] | type[ExtensionProtocol[INSTANCE, SETTINGS]] | Callable[[], ExtensionProtocol[INSTANCE, SETTINGS]]
|
Extension instance, extension class, or factory callable. |
required |
use_overwrite
|
bool
|
Use the active |
True
|
on_conflict
|
Literal['error', 'keep', 'replace']
|
Strategy used when an extension with the same name is
already present. Supported values are |
'error'
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If extensions support is not enabled. |
ValueError
|
If |
KeyError
|
If the extension name already exists and |
Examples:
>>> monkay.add_extension(MyExtension())
>>> monkay.add_extension(MyExtension, on_conflict="replace")
Notes
on_conflict is validated even when no name collision happens.
This keeps behavior deterministic across input data sets.
Source code in monkay/_monkay_extensions.py
with_extensions
¶
Temporarily sets and yields a new set of extensions for the Monkay instance.
This method allows temporarily overriding the registered extensions within a context. It yields the provided extensions (or None to temporarily use the real extensions), and then restores the original extensions after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extensions
|
dict[str, ExtensionProtocol[INSTANCE, SETTINGS]] | None
|
The new set of extensions to use within the context, or None to temporarily use the real extensions. |
required |
apply_extensions
|
bool
|
If True, applies the temporary extensions immediately after setting them. |
False
|
Yields:
| Type | Description |
|---|---|
Generator[dict[str, ExtensionProtocol[INSTANCE, SETTINGS]] | None]
|
The provided extensions (or None). |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for extensions. |
Source code in monkay/_monkay_extensions.py
set_instance
¶
Sets the instance managed by Monkay and optionally applies extensions.
This method updates the instance associated with the Monkay object. It also allows applying extensions immediately after setting the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
INSTANCE | None
|
The new instance to set, or None to unset the instance. |
required |
apply_extensions
|
bool
|
If True, applies the registered extensions after setting the instance. |
True
|
use_extensions_overwrite
|
bool
|
If True, uses the extensions from the |
True
|
Returns:
| Type | Description |
|---|---|
INSTANCE | None
|
The set instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for instances. |
RuntimeError
|
If another extension application process is already active in the same context. |
Source code in monkay/_monkay_instance.py
with_instance
¶
Temporarily sets and yields a new instance for the Monkay object within a context.
This context manager allows temporarily overriding the instance associated with the Monkay object. It yields the provided instance and then restores the original instance after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
INSTANCE | None
|
The new instance to use within the context, or None to temporarily unset the instance. |
required |
apply_extensions
|
bool
|
If True, applies the registered extensions after setting the instance. |
False
|
use_extensions_overwrite
|
bool
|
If True, uses the extensions from the |
True
|
Yields:
| Type | Description |
|---|---|
Generator[INSTANCE | None]
|
The provided instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Monkay is not enabled for instances. |
RuntimeError
|
If another extension application process is already active in the same context. |
Source code in monkay/_monkay_instance.py
Base Helpers¶
monkay.base
¶
InGlobalsDict
¶
Bases: Exception
Source code in monkay/base.py
UnsetError
¶
Bases: RuntimeError
Source code in monkay/base.py
load
¶
Dynamically loads an object from a module given its path.
This function takes a string representing the path to an object within a module and dynamically imports the module and retrieves the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the object, in the format "module:object" or "module.object". |
required |
allow_splits
|
str
|
A string specifying the allowed separators for module and object names. Defaults to ":." allowing both ":" and "." as separators. |
':.'
|
package
|
None | str
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The loaded object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path is invalid or cannot be parsed. |
ImportError
|
If the module cannot be imported. |
Source code in monkay/base.py
load_any
¶
Dynamically loads any of the specified attributes from a module.
This function takes a module path and a collection of attribute names. It attempts to import the module and retrieve each attribute in the given order. If any of the attributes are found, it returns the first one found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the module. |
required |
attrs
|
Collection[str]
|
A collection of attribute names to search for. |
required |
non_first_deprecated
|
bool
|
If True, issues deprecation warnings for all found attributes except the first one. |
False
|
package
|
None | str
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
Any | None
|
The first found attribute, or None if none of the attributes are found. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the module cannot be imported or none of the attributes are found. |
DeprecationWarning
|
If |
Source code in monkay/base.py
absolutify_import
¶
Converts a relative import path to an absolute import path.
This function takes an import path and a package name and converts the relative import path to an absolute path by prepending the package name and adjusting for relative levels (e.g., "..module").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
import_path
|
str
|
The import path to absolutify. |
required |
package
|
str | None
|
The package name to use as a base for relative imports. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The absolute import path. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the import path is invalid or tries to cross parent boundaries. |
Source code in monkay/base.py
get_value_from_settings
¶
Retrieves a value from a settings object, supporting both attribute and dictionary access.
This function attempts to retrieve a value from a settings object. It first tries to access the value as an attribute. If that fails, it tries to access the value as a dictionary key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
Any
|
The settings object to retrieve the value from. |
required |
name
|
str
|
The name of the attribute or key to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The retrieved value. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If the name is not found as an attribute and the settings object does not support dictionary access. |
KeyError
|
If the name is not found as a key in the settings object and attribute access also fails. |
Source code in monkay/base.py
evaluate_preloads
¶
Evaluates preload modules or functions specified in settings.
This function iterates through a collection of preload paths, imports the modules, and optionally calls specified functions within those modules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preloads
|
Iterable[str]
|
An iterable of preload paths, in the format "module" or "module:function". |
required |
ignore_import_errors
|
bool
|
If True, ignores import errors and continues processing. |
True
|
package
|
str | None
|
The package name to use as a context for relative imports. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if all preloads were successfully evaluated, False otherwise. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If a module cannot be imported and |
Source code in monkay/base.py
Cages¶
monkay.cages
¶
forbidden_names
module-attribute
¶
Cage
¶
Bases: Generic[T]
A container class that manages a value with context-aware modifications and synchronization.
Source code in monkay/cages.py
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 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 370 371 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 | |
monkay_context_var
instance-attribute
¶
A context variable that stores the current value and update timestamp within a specific context. This allows for context-specific modifications and retrieval of the value.
monkay_deep_copy
instance-attribute
¶
A boolean indicating whether deep copies should be used when modifying the value. If True, modifications will create deep copies of the original value to avoid unintended side effects.
monkay_use_wrapper_for_reads
instance-attribute
¶
A boolean indicating whether a wrapper should be used for read operations. If True, read operations will be wrapped in a context manager to ensure consistency.
monkay_update_fn
instance-attribute
¶
An optional function that defines how to update the value when modifications are made. This function takes the current value and the new value as input and returns the updated value.
monkay_name
instance-attribute
¶
A name associated with the Cage instance, used for identification and debugging purposes.
monkay_original
instance-attribute
¶
The original value stored in the Cage instance. This attribute holds the initial value that is managed by the Cage.
monkay_original_last_update
instance-attribute
¶
A timestamp indicating the last time the original value was updated. This timestamp is used to track changes and ensure consistency.
monkay_original_last_update_lock
instance-attribute
¶
An optional lock used to synchronize updates to the original value. This lock prevents race conditions when multiple threads or processes try to update the value concurrently.
monkay_original_wrapper
instance-attribute
¶
A context manager used to wrap access to the original value, ensuring consistency and synchronization. This wrapper provides a controlled environment for read and write operations on the original value.
monkay_forward
classmethod
¶
Creates a wrapper function that forwards method calls to the wrapped object.
This class method generates a wrapper function that intercepts method calls to the Cage instance and forwards them to the wrapped object, ensuring that the object is updated or copied as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_type
|
type
|
The type of the wrapped object. |
required |
name
|
str
|
The name of the method to forward. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A wrapper function that forwards method calls. |
Source code in monkay/cages.py
monkay_refresh_copy
¶
monkay_refresh_copy(*, obj=Undefined, use_wrapper=None, _monkay_dict=None)
Refreshes the context variable with a copy of the original object.
This method updates the context variable with a fresh copy of the original object, optionally using a wrapper and handling deep or shallow copies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
T | type[Undefined]
|
An optional object to use instead of creating a copy. |
Undefined
|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The refreshed object. |
Source code in monkay/cages.py
monkay_conditional_update_copy
¶
Retrieves a context-aware copy of the original object, updating it if necessary.
This method retrieves a copy of the original object, updating it based on context and update functions. It checks if the context variable is set and if the original object has been updated, and applies the update function if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The context-aware copy of the object. |
Source code in monkay/cages.py
monkay_proxied
¶
Returns a proxied version of the object, ensuring context-aware updates.
This method returns a context-aware copy of the object, optionally using a wrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The proxied object. |
Source code in monkay/cages.py
monkay_with_override
¶
Temporarily overrides the context variable with a new value within a context.
This context manager temporarily sets the context variable to a new value and yields it. After the context exits, the original context variable is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
allow_value_update
|
bool
|
If True, allows the value to be updated by the update function. If False, the value will not be updated. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The new value. |
Source code in monkay/cages.py
monkay_with_original
¶
Temporarily accesses the original value within a context, optionally updating it.
This context manager yields the original value, optionally using a wrapper and updating the last update timestamp after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool
|
If True, uses the original wrapper when accessing the original value. |
True
|
update_after
|
bool
|
If True, updates the last update timestamp after the context exits. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The original value. |
Source code in monkay/cages.py
monkay_set
¶
Sets the context variable to a new value and returns a token.
This method sets the context variable to a new value and returns a token that can be used to reset the context variable to its previous value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
Returns:
| Type | Description |
|---|---|
Token
|
A token that can be used to reset the context variable. |
Source code in monkay/cages.py
monkay_get
¶
Retrieves the current value of the context variable, or a default value if it's not set.
This method retrieves the current value of the context variable. If the context variable is not set, it returns the original value or a default value if provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
T | DEFAULT | None
|
The default value to return if the context variable is not set. |
None
|
Returns:
| Type | Description |
|---|---|
T | DEFAULT | None
|
The current value of the context variable, the original value, or the default value. |
Source code in monkay/cages.py
monkay_reset
¶
Resets the context variable to its previous value using a token.
This method resets the context variable to its previous value using a token returned by monkay_set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Token
|
The token returned by |
required |
Source code in monkay/cages.py
TransparentCage
¶
Bases: Cage
A transparent Cage subclass that exposes context variable attributes directly.
This subclass of Cage allows direct access to context variable attributes (e.g., 'get', 'set', 'reset') without requiring the 'monkay_' prefix. It provides a more transparent interface for interacting with context-aware values.
Source code in monkay/cages.py
monkay_context_var
instance-attribute
¶
A context variable that stores the current value and update timestamp within a specific context. This allows for context-specific modifications and retrieval of the value.
monkay_deep_copy
instance-attribute
¶
A boolean indicating whether deep copies should be used when modifying the value. If True, modifications will create deep copies of the original value to avoid unintended side effects.
monkay_use_wrapper_for_reads
instance-attribute
¶
A boolean indicating whether a wrapper should be used for read operations. If True, read operations will be wrapped in a context manager to ensure consistency.
monkay_update_fn
instance-attribute
¶
An optional function that defines how to update the value when modifications are made. This function takes the current value and the new value as input and returns the updated value.
monkay_name
instance-attribute
¶
A name associated with the Cage instance, used for identification and debugging purposes.
monkay_original
instance-attribute
¶
The original value stored in the Cage instance. This attribute holds the initial value that is managed by the Cage.
monkay_original_last_update
instance-attribute
¶
A timestamp indicating the last time the original value was updated. This timestamp is used to track changes and ensure consistency.
monkay_original_last_update_lock
instance-attribute
¶
An optional lock used to synchronize updates to the original value. This lock prevents race conditions when multiple threads or processes try to update the value concurrently.
monkay_original_wrapper
instance-attribute
¶
A context manager used to wrap access to the original value, ensuring consistency and synchronization. This wrapper provides a controlled environment for read and write operations on the original value.
monkay_forward
classmethod
¶
Creates a wrapper function that forwards method calls to the wrapped object.
This class method generates a wrapper function that intercepts method calls to the Cage instance and forwards them to the wrapped object, ensuring that the object is updated or copied as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_type
|
type
|
The type of the wrapped object. |
required |
name
|
str
|
The name of the method to forward. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A wrapper function that forwards method calls. |
Source code in monkay/cages.py
monkay_refresh_copy
¶
monkay_refresh_copy(*, obj=Undefined, use_wrapper=None, _monkay_dict=None)
Refreshes the context variable with a copy of the original object.
This method updates the context variable with a fresh copy of the original object, optionally using a wrapper and handling deep or shallow copies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
T | type[Undefined]
|
An optional object to use instead of creating a copy. |
Undefined
|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The refreshed object. |
Source code in monkay/cages.py
monkay_conditional_update_copy
¶
Retrieves a context-aware copy of the original object, updating it if necessary.
This method retrieves a copy of the original object, updating it based on context and update functions. It checks if the context variable is set and if the original object has been updated, and applies the update function if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
_monkay_dict
|
dict | None
|
An optional dictionary to use instead of the Cage's |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The context-aware copy of the object. |
Source code in monkay/cages.py
monkay_proxied
¶
Returns a proxied version of the object, ensuring context-aware updates.
This method returns a context-aware copy of the object, optionally using a wrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool | None
|
If True, uses the original wrapper when accessing the original object.
If None, uses the Cage's default |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The proxied object. |
Source code in monkay/cages.py
monkay_with_override
¶
Temporarily overrides the context variable with a new value within a context.
This context manager temporarily sets the context variable to a new value and yields it. After the context exits, the original context variable is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
allow_value_update
|
bool
|
If True, allows the value to be updated by the update function. If False, the value will not be updated. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The new value. |
Source code in monkay/cages.py
monkay_with_original
¶
Temporarily accesses the original value within a context, optionally updating it.
This context manager yields the original value, optionally using a wrapper and updating the last update timestamp after the context exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_wrapper
|
bool
|
If True, uses the original wrapper when accessing the original value. |
True
|
update_after
|
bool
|
If True, updates the last update timestamp after the context exits. |
True
|
Yields:
| Type | Description |
|---|---|
Generator[T]
|
The original value. |
Source code in monkay/cages.py
monkay_set
¶
Sets the context variable to a new value and returns a token.
This method sets the context variable to a new value and returns a token that can be used to reset the context variable to its previous value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The new value to set the context variable to. |
required |
Returns:
| Type | Description |
|---|---|
Token
|
A token that can be used to reset the context variable. |
Source code in monkay/cages.py
monkay_get
¶
Retrieves the current value of the context variable, or a default value if it's not set.
This method retrieves the current value of the context variable. If the context variable is not set, it returns the original value or a default value if provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
T | DEFAULT | None
|
The default value to return if the context variable is not set. |
None
|
Returns:
| Type | Description |
|---|---|
T | DEFAULT | None
|
The current value of the context variable, the original value, or the default value. |
Source code in monkay/cages.py
monkay_reset
¶
Resets the context variable to its previous value using a token.
This method resets the context variable to its previous value using a token returned by monkay_set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Token
|
The token returned by |
required |
Source code in monkay/cages.py
ASGI¶
monkay.asgi
¶
ASGI lifecycle utilities and compatibility helpers.
This module provides two production-oriented helpers:
- :class:
Lifespan, a tiny in-process ASGI server-side lifespan driver that can be used from tests or integration harnesses. - :func:
LifespanHook, an adapter that helps applications integrate custom startup/shutdown setup logic without forcing framework-specific coupling.
ASGIApp
module-attribute
¶
ASGIApp = Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]]
Lifespan
¶
Bases: Generic[BoundASGIApp]
Drive the ASGI lifespan protocol as an in-process server harness.
The instance emulates a minimal server-side lifespan loop:
it sends lifespan.startup and lifespan.shutdown messages to an ASGI
application and consumes responses from the app.
The class is intentionally lightweight and fully async, so it can be used in tests and orchestration code that needs deterministic startup/shutdown boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
BoundASGIApp
|
ASGI application callable supporting the lifespan protocol. |
required |
timeout
|
None | int | float
|
Optional timeout applied by |
None
|
Source code in monkay/asgi.py
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 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 | |
start_raw
async
¶
Run lifespan startup without applying timeout policy.
Returns:
| Type | Description |
|---|---|
BoundASGIApp
|
The wrapped ASGI application for convenience/chaining. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If startup fails or returns an unexpected message. |
BaseException
|
Re-raises startup cancellation/errors after ensuring spawned lifespan task cleanup. |
Source code in monkay/asgi.py
shutdown_raw
async
¶
Run lifespan shutdown without applying timeout policy.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the app reports shutdown failure or if the lifespan task crashes during shutdown. |
Source code in monkay/asgi.py
MuteInteruptException
¶
LifespanHook
¶
LifespanHook(app: BoundASGIApp, *, setup: Callable[[], Awaitable[AsyncExitStack]] | None = None, do_forward: bool = True) -> BoundASGIApp
LifespanHook(app: None, *, setup: Callable[[], Awaitable[AsyncExitStack]] | None = None, do_forward: bool = True) -> Callable[[BoundASGIApp], BoundASGIApp]
Wrap an ASGI app with optional setup/teardown hooks.
The wrapper can either:
- forward lifespan traffic to the underlying app (
do_forward=True), or - fully handle startup/shutdown completion messages itself
(
do_forward=False).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
BoundASGIApp | None
|
Optional ASGI app to wrap. When |
None
|
setup
|
Callable[[], Awaitable[AsyncExitStack]] | None
|
Optional async callable returning an :class: |
None
|
do_forward
|
bool
|
Whether lifespan messages should be forwarded to the wrapped app after setup/teardown interception. |
True
|
Returns:
| Type | Description |
|---|---|
BoundASGIApp | Callable[[BoundASGIApp], BoundASGIApp]
|
Wrapped ASGI application, or a decorator factory if |
Examples:
>>> wrapped = LifespanHook(app, setup=my_setup, do_forward=False)
>>> async with Lifespan(wrapped):
... pass
Notes
Setup state is scoped to a single lifespan invocation. Reusing the same wrapped app across multiple lifespan sessions is safe.
Source code in monkay/asgi.py
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 | |
Types¶
monkay.types
¶
SETTINGS_DEFINITION_BASE_TYPE
module-attribute
¶
SETTINGS_DEFINITION_BASE_TYPE = SETTINGS_T | type[SETTINGS_T] | str | None
SETTINGS_DEFINITION_TYPE
module-attribute
¶
SETTINGS_DEFINITION_TYPE = SETTINGS_DEFINITION_BASE_TYPE[SETTINGS_T] | Callable[[], SETTINGS_DEFINITION_BASE_TYPE[SETTINGS_T]]
ASGIApp
module-attribute
¶
ASGIApp = Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]]
SortedExportsEntry
¶
Bases: NamedTuple
Represents an entry in a sorted list of module exports.
This class encapsulates information about a module export, including its category, name, and path.
Source code in monkay/types.py
DeprecatedImport
¶
Bases: TypedDict
Represents a deprecated import with optional deprecation details.
This class defines the structure for deprecated imports, including the import path, reason for deprecation, and a replacement attribute.
Source code in monkay/types.py
EvaluateSettingsParameters
¶
Bases: TypedDict
Source code in monkay/types.py
PRE_ADD_LAZY_IMPORT_HOOK
¶
Bases: Protocol
A protocol defining the signature for a hook that modifies lazy import definitions before they are added.
This protocol specifies the expected signature for a hook function that can be used to modify lazy import definitions before they are added to the module. It supports both regular lazy imports and deprecated lazy imports.