Index
sparkwheel: A powerful YAML-based configuration system with references, expressions, and dynamic instantiation.
Uses YAML format only.
BaseError
Bases: Exception
Base exception for sparkwheel with rich error context.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
The error message |
|
source_location |
Optional location in config file where error occurred |
|
suggestion |
Optional helpful suggestion for fixing the error |
Source code in src/sparkwheel/utils/exceptions.py
_format_message()
Format error message with source location and suggestions.
Critical info (file:line) is on the first line for Rich compatibility, since Rich's traceback only shows the first line of exception messages.
Source code in src/sparkwheel/utils/exceptions.py
_get_config_snippet()
Extract and format a code snippet from the config file.
Source code in src/sparkwheel/utils/exceptions.py
CircularReferenceError
Component
Bases: Item, Instantiable
Component that can be instantiated from configuration.
Uses a dictionary with string keys to represent a Python class or function that can be dynamically instantiated. Other keys are passed as arguments to the target component.
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
Configuration content |
required |
id
|
str
|
Identifier for this config item, defaults to "" |
''
|
Note
Special configuration keys:
_target_: Full module path (e.g., "collections.Counter")_requires_: Dependencies to evaluate/instantiate first_disabled_: Skip instantiation if True_mode_: Instantiation mode:"default": Returns component(**kwargs)"callable": Returns functools.partial(component, **kwargs)"debug": Returns pdb.runcall(component, **kwargs)
Source code in src/sparkwheel/items.py
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 | |
_suggest_similar_modules(target)
Suggest similar valid module names using fuzzy matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str
|
The module path that couldn't be found (e.g., 'torch.optim.Adamfad') |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
A helpful suggestion string, or None if no good suggestions found. |
Source code in src/sparkwheel/items.py
instantiate(**kwargs)
Instantiate component based on self.config content.
The target component must be a class or a function, otherwise, return None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
Any
|
args to override / add the config args when instantiation. |
{}
|
Source code in src/sparkwheel/items.py
is_disabled()
Utility function used in instantiate() to check whether to skip the instantiation.
Source code in src/sparkwheel/items.py
is_instantiable(config)
staticmethod
Check whether this config represents a class or function that is to be instantiated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
input config content to check. |
required |
Source code in src/sparkwheel/items.py
resolve_args()
Utility function used in instantiate() to resolve the arguments from current config content.
Source code in src/sparkwheel/items.py
resolve_module_name()
Resolve the target module name from configuration.
Requires full module path (e.g., "collections.Counter"). No automatic module discovery is performed.
Returns:
| Type | Description |
|---|---|
|
str or callable: The module path or callable from target |
Source code in src/sparkwheel/items.py
Config
Configuration management with continuous validation, coercion, resolved references, and instantiation.
Main entry point for loading, managing, and resolving configurations. Supports YAML files with resolved references (@), raw references (%), expressions ($), and dynamic instantiation (target).
Example
from sparkwheel import Config
# Create and load from file
config = Config(schema=MySchema).update("config.yaml")
# Or chain multiple sources
config = (Config(schema=MySchema)
.update("base.yaml")
.update("override.yaml")
.update({"model::lr": 0.001}))
# Access raw values
lr = config.get("model::lr")
# Set values (validates automatically if schema provided)
config.set("model::dropout", 0.1)
# Freeze to prevent modifications
config.freeze()
# Resolve references and instantiate
model = config.resolve("model")
everything = config.resolve()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
globals
|
dict[str, Any] | None
|
Pre-imported packages for expressions (e.g., {"torch": "torch"}) |
None
|
schema
|
type | None
|
Dataclass schema for continuous validation |
None
|
coerce
|
bool
|
Auto-convert compatible types (default: True) |
True
|
strict
|
bool
|
Reject fields not in schema (default: True) |
True
|
allow_missing
|
bool
|
Allow MISSING sentinel values (default: False) |
False
|
Source code in src/sparkwheel/config.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 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 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | |
__contains__(id)
Check if ID exists in config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
ID path to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if exists, False otherwise |
Source code in src/sparkwheel/config.py
__getitem__(id)
Get config value by ID (subscript access).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Configuration path |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Config value at that path |
Example
config = Config.load({"model": {"lr": 0.001}}) config["model::lr"] 0.001
Source code in src/sparkwheel/config.py
__init__(data=None, *, globals=None, schema=None, coerce=True, strict=True, allow_missing=False)
Initialize Config container.
Normally starts empty - use update() to load data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any] | None
|
Initial data (internal/testing use only, not validated) |
None
|
globals
|
dict[str, Any] | None
|
Pre-imported packages for expression evaluation |
None
|
schema
|
type | None
|
Dataclass schema for continuous validation |
None
|
coerce
|
bool
|
Auto-convert compatible types |
True
|
strict
|
bool
|
Reject fields not in schema |
True
|
allow_missing
|
bool
|
Allow MISSING sentinel values |
False
|
Examples:
Source code in src/sparkwheel/config.py
__repr__()
__setitem__(id, value)
Set config value by ID (subscript access).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Configuration path |
required |
value
|
Any
|
Value to set |
required |
Example
config = Config.load({}) config["model::lr"] = 0.001
Source code in src/sparkwheel/config.py
_apply_path_updates(source)
Apply nested path updates (e.g., model::lr=value, =model=replace, ~old::param=null).
Source code in src/sparkwheel/config.py
_apply_structural_update(source)
Apply structural update with operators.
_delete_nested_key(key)
Delete a key, supporting nested paths with ::.
Source code in src/sparkwheel/config.py
_get_by_id(id)
Get config value by ID path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
ID path (e.g., "model::lr") |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Config value at that path |
Raises:
| Type | Description |
|---|---|
KeyError
|
If path not found |
Source code in src/sparkwheel/config.py
_invalidate_resolution()
_parse(reset=True)
Parse config tree and prepare for resolution.
Internal method called automatically by resolve().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reset
|
bool
|
Whether to reset the resolver before parsing (default: True) |
True
|
Source code in src/sparkwheel/config.py
_update_from_config(source)
Update from another Config instance.
_update_from_file(source)
Load and update from a file.
Source code in src/sparkwheel/config.py
_update_from_override_string(override)
Parse and apply a single override string (e.g., 'key=value', '=key=value', '~key').
_uses_nested_paths(source)
export_config_file(config, filepath, **kwargs)
staticmethod
Export config to YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Config dict to export |
required |
filepath
|
PathLike
|
Target file path |
required |
kwargs
|
Any
|
Additional arguments for yaml.safe_dump |
{}
|
Source code in src/sparkwheel/config.py
freeze()
Freeze config to prevent further modifications.
After freezing: - set() raises FrozenConfigError - update() raises FrozenConfigError - resolve() still works (read-only) - get() still works (read-only)
Example
config = Config(schema=MySchema).update("config.yaml") config.freeze() config.set("model::lr", 0.001) # Raises FrozenConfigError
Source code in src/sparkwheel/config.py
get(id='', default=None)
Get raw config value (unresolved).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Configuration path (use :: for nesting, e.g., "model::lr") Empty string returns entire config |
''
|
default
|
Any
|
Default value if id not found |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Raw configuration value (resolved references not resolved, raw references not expanded) |
Example
config = Config.load({"model": {"lr": 0.001, "ref": "@model::lr"}}) config.get("model::lr") 0.001 config.get("model::ref") "@model::lr" # Unresolved resolved reference
Source code in src/sparkwheel/config.py
is_frozen()
resolve(id='', instantiate=True, eval_expr=True, lazy=True, default=None)
Resolve resolved references (@) and return parsed config.
Automatically parses config on first call. Resolves @ resolved references (follows them to get instantiated/evaluated values), evaluates $ expressions, and instantiates target components. Note: % raw references are expanded during preprocessing (before this stage).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Config path to resolve (empty string for entire config) |
''
|
instantiate
|
bool
|
Whether to instantiate components with target |
True
|
eval_expr
|
bool
|
Whether to evaluate $ expressions |
True
|
lazy
|
bool
|
Whether to use cached resolution |
True
|
default
|
Any
|
Default value if id not found (returns default.get_config() if Item) |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Resolved value (instantiated objects, evaluated expressions, etc.) |
Example
config = Config.load({ ... "lr": 0.001, ... "doubled": "$@lr * 2", ... "optimizer": { ... "target": "torch.optim.Adam", ... "lr": "@lr" ... } ... }) config.resolve("lr") 0.001 config.resolve("doubled") 0.002 optimizer = config.resolve("optimizer") type(optimizer).name 'Adam'
Source code in src/sparkwheel/config.py
set(id, value)
Set config value, creating paths as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Configuration path (use :: for nesting) |
required |
value
|
Any
|
Value to set |
required |
Raises:
| Type | Description |
|---|---|
FrozenConfigError
|
If config is frozen |
Example
config = Config() config.set("model::lr", 0.001) config.get("model::lr") 0.001
Source code in src/sparkwheel/config.py
unfreeze()
update(source)
Update configuration with changes from another source.
Auto-detects strings as either file paths or CLI overrides: - Strings with '=' are parsed as overrides (e.g., "key=value", "=key=value", "~key") - Strings without '=' are treated as file paths - Dicts and Config instances work as before
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
PathLike | dict[str, Any] | Config | str
|
File path, override string, dict, or Config instance to update from |
required |
Returns:
| Type | Description |
|---|---|
Config
|
self (for chaining) |
Operators
- key=value - Compose (default): merge dict or extend list
- =key=value - Replace operator: completely replace value
- ~key - Remove operator: delete key (idempotent)
Examples:
>>> # Chain multiple updates (mixed files and overrides)
>>> config = (Config(schema=MySchema)
... .update("base.yaml")
... .update("exp.yaml")
... .update("optimizer::lr=0.01")
... .update("=model={'_target_': 'MyModel'}")
... .update("~debug"))
>>> # Update from another Config instance
>>> config1 = Config()
>>> config2 = Config().update({"model::lr": 0.001})
>>> config1.update(config2)
Source code in src/sparkwheel/config.py
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 | |
validate(schema)
Validate configuration against a dataclass schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
type
|
Dataclass type defining the expected structure and types |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If configuration doesn't match schema |
TypeError
|
If schema is not a dataclass |
Example
from dataclasses import dataclass @dataclass ... class ModelConfig: ... hidden_size: int ... dropout: float config = Config.load({"hidden_size": 512, "dropout": 0.1}) config.validate(ModelConfig) # Passes bad_config = Config.load({"hidden_size": "not an int"}) bad_config.validate(ModelConfig) # Raises ValidationError
Source code in src/sparkwheel/config.py
ConfigKeyError
Bases: BaseError
Raised when a config key is not found.
Supports smart suggestions and available keys display.
Source code in src/sparkwheel/utils/exceptions.py
__init__(message, source_location=None, suggestion=None, missing_key=None, available_keys=None, config_context=None)
Initialize ConfigKeyError with enhanced context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message |
required |
source_location
|
SourceLocation | None
|
Location where error occurred |
None
|
suggestion
|
str | None
|
Manual suggestion (optional) |
None
|
missing_key
|
str | None
|
The key that wasn't found |
None
|
available_keys
|
list[str] | None
|
List of available keys for suggestions |
None
|
config_context
|
dict[str, Any] | None
|
The config dict where the key wasn't found (for displaying available keys) |
None
|
Source code in src/sparkwheel/utils/exceptions.py
_generate_suggestion()
Generate smart suggestion with typo detection and available keys.
Source code in src/sparkwheel/utils/exceptions.py
ConfigMergeError
Bases: BaseError
Raised when configuration merge operation fails.
This is typically raised when using operators (= or ~) incorrectly: - Using ~ on a non-existent key - Using ~ with invalid value (must be null, empty, or list) - Type mismatch during merge (e.g., trying to merge dict into list)
Source code in src/sparkwheel/utils/exceptions.py
EvaluationError
Expression
Bases: Item
Executable expression that evaluates Python code.
Expressions start with $ and are evaluated using Python's eval(),
or imported if they're import statements.
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
Expression string starting with |
required |
id
|
str
|
Identifier for this config item, defaults to "" |
''
|
globals
|
dict[str, Any] | None
|
Additional global context for evaluation |
None
|
See Also
Source code in src/sparkwheel/items.py
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 | |
_parse_import_string(import_string)
parse single import statement such as "from pathlib import Path"
Source code in src/sparkwheel/items.py
evaluate(globals=None, locals=None)
Evaluate the expression and return the result.
Uses Python's eval() to execute the expression string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
globals
|
dict[str, Any] | None
|
Additional global symbols for evaluation |
None
|
locals
|
dict[str, Any] | None
|
Additional local symbols for evaluation |
None
|
Returns:
| Type | Description |
|---|---|
str | Any | None
|
Evaluation result, or None if not an expression |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If evaluation fails |
Source code in src/sparkwheel/items.py
is_expression(config)
classmethod
Check whether the config is an executable expression string.
Currently, a string starts with "$" character is interpreted as an expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any] | list[Any] | str
|
input config content to check. |
required |
Source code in src/sparkwheel/items.py
is_import_statement(config)
classmethod
Check whether the config is an import statement (a special case of expression).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any] | list[Any] | str
|
input config content to check. |
required |
Source code in src/sparkwheel/items.py
FrozenConfigError
Bases: BaseError
Raised when attempting to modify a frozen config.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
Error description |
|
field_path |
Path that was attempted to modify |
Source code in src/sparkwheel/utils/exceptions.py
Instantiable
Bases: ABC
Base class for an instantiable object.
Source code in src/sparkwheel/items.py
instantiate(*args, **kwargs)
abstractmethod
Instantiate the target component and return the instance.
is_disabled(*args, **kwargs)
abstractmethod
Return a boolean flag to indicate whether the object should be instantiated.
Source code in src/sparkwheel/items.py
InstantiationError
Item
Basic data structure to represent a configuration item.
A Item instance can optionally have a string id, so that other items can refer to it.
It has a build-in config property to store the configuration object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
content of a config item, can be objects of any types, a configuration resolver may interpret the content to generate a configuration object. |
required |
id
|
str
|
name of the current config item, defaults to empty string. |
''
|
source_location
|
SourceLocation | None
|
optional location in source file where this config item was defined. |
None
|
Source code in src/sparkwheel/items.py
get_config()
get_id()
update_config(config)
Replace the content of self.config with new config.
A typical usage is to modify the initial config content at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
content of a |
required |
ModuleNotFoundError
Resolver
Resolve references between Items.
Manages Items and resolves resolved reference strings (starting with @) by substituting them with their corresponding resolved values (instantiated objects, evaluated expressions, etc.).
Example
Resolved references can use :: separator for nested access:
- Dictionary keys: @config::subkey
- List indices: @list::0::subitem
Source code in src/sparkwheel/resolver.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 | |
__init__(items=None)
Initialize resolver with optional items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[Item] | None
|
Optional list of Items to add during initialization |
None
|
Source code in src/sparkwheel/resolver.py
_resolve_one_item(id, waiting_list=None, _depth=0, instantiate=True, eval_expr=True, default=None)
Internal recursive resolution implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
ID to resolve |
required |
waiting_list
|
set[str] | None
|
Set of IDs currently being resolved (for cycle detection) |
None
|
_depth
|
int
|
Current recursion depth (for DoS prevention) |
0
|
instantiate
|
bool
|
Whether to instantiate components |
True
|
eval_expr
|
bool
|
Whether to evaluate expressions |
True
|
default
|
Any
|
Default value if not found |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Resolved value |
Raises:
| Type | Description |
|---|---|
RecursionError
|
If max depth exceeded |
CircularReferenceError
|
If circular reference detected |
ConfigKeyError
|
If reference not found |
Source code in src/sparkwheel/resolver.py
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 | |
add_item(item)
Add a Item to resolve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
Item
|
Item to add |
required |
Source code in src/sparkwheel/resolver.py
add_items(items)
Add multiple Items at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[Item]
|
List of Items to add |
required |
find_refs_in_config(config, id, refs=None)
classmethod
Recursively find all references in config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
Config to search |
required |
id
|
str
|
Current ID path |
required |
refs
|
dict[str, int] | None
|
Accumulated references dict |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict of reference IDs to counts |
Source code in src/sparkwheel/resolver.py
get_item(id, resolve=False, **kwargs)
Get Item by id, optionally resolved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
ID of the config item |
required |
resolve
|
bool
|
Whether to resolve the item (default: False) |
False
|
**kwargs
|
Any
|
Additional arguments for resolution |
{}
|
Returns:
| Type | Description |
|---|---|
Item | None
|
Item if found, None otherwise (or resolved value if resolve=True) |
Source code in src/sparkwheel/resolver.py
is_resolved()
iter_subconfigs(id, config)
classmethod
Iterate over sub-configs with IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Current ID path |
required |
config
|
Any
|
Config to iterate (dict or list) |
required |
Yields:
| Type | Description |
|---|---|
tuple[str, str, Any]
|
Tuples of (key, sub_id, value) |
Source code in src/sparkwheel/resolver.py
match_refs_pattern(value)
classmethod
Find reference patterns in a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String to search for references |
required |
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict mapping reference IDs to occurrence counts |
Source code in src/sparkwheel/resolver.py
normalize_id(id)
classmethod
Normalize ID to string format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str | int
|
ID to normalize |
required |
Returns:
| Type | Description |
|---|---|
str
|
String ID |
reset()
resolve(id='', instantiate=True, eval_expr=True, default=None)
Resolve a config item and return the result.
Resolves all references, instantiates components (if requested), and evaluates expressions (if requested). Results are cached for efficiency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
ID of item to resolve (empty string for root) |
''
|
instantiate
|
bool
|
Whether to instantiate components with target |
True
|
eval_expr
|
bool
|
Whether to evaluate expressions starting with $ |
True
|
default
|
Any
|
Default value if id not found |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Resolved value (instantiated object, evaluated result, or raw value) |
Raises:
| Type | Description |
|---|---|
ConfigKeyError
|
If id not found and no default provided |
CircularReferenceError
|
If circular reference detected |
Source code in src/sparkwheel/resolver.py
split_id(id, last=False)
classmethod
Split ID string by separator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str | int
|
ID to split |
required |
last
|
bool
|
If True, only split rightmost part |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of ID components |
Source code in src/sparkwheel/resolver.py
update_config_with_refs(config, id, refs=None)
classmethod
Update config by replacing references with resolved values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
Config to update |
required |
id
|
str
|
Current ID path |
required |
refs
|
dict[str, Any] | None
|
Dict of resolved references |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Config with references replaced |
Source code in src/sparkwheel/resolver.py
update_refs_pattern(value, refs)
classmethod
Replace reference patterns with resolved values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String containing references |
required |
refs
|
dict[str, Any]
|
Dict of resolved references |
required |
Returns:
| Type | Description |
|---|---|
str
|
String with references replaced |
Source code in src/sparkwheel/resolver.py
SourceLocation
dataclass
Tracks the source location of a config item.
Source code in src/sparkwheel/utils/exceptions.py
ValidationError
Bases: BaseError
Raised when configuration validation fails.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
Error description |
|
field_path |
Dot-separated path to the invalid field (e.g., "model.optimizer.lr") |
|
expected_type |
The type that was expected |
|
actual_value |
The value that failed validation |
|
source_location |
Optional location in source file where error occurred |
Source code in src/sparkwheel/schema.py
__init__(message, field_path='', expected_type=None, actual_value=None, source_location=None)
Initialize validation error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable error message |
required |
field_path
|
str
|
Dot-separated path to invalid field |
''
|
expected_type
|
type | None
|
Expected type for the field |
None
|
actual_value
|
Any
|
The actual value that failed validation |
None
|
source_location
|
SourceLocation | None
|
Source location where the invalid value was defined |
None
|
Source code in src/sparkwheel/schema.py
apply_operators(base, override)
Apply configuration changes with composition-by-default semantics.
Default behavior: Compose (merge dicts, extend lists) Operators: =key: value - Replace operator: completely replace value (override default) ~key: null - Remove operator: delete key or list items (idempotent) key: value - Compose (default): merge dict or extend list
Composition-by-Default Philosophy
- Dicts merge recursively by default (preserves existing keys)
- Lists extend by default (append new items)
- Only scalars and type mismatches replace
- Use = to explicitly replace entire dicts or lists
- Use ~ to delete keys (idempotent - no error if missing)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
dict[str, Any]
|
Base configuration dict |
required |
override
|
dict[str, Any]
|
Override configuration dict with optional =/~ operators |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Merged configuration dict |
Raises:
| Type | Description |
|---|---|
ConfigMergeError
|
If operators are used incorrectly |
Examples:
>>> # Default: Dicts merge
>>> base = {"a": 1, "b": {"x": 1, "y": 2}}
>>> override = {"b": {"x": 10}}
>>> apply_operators(base, override)
{"a": 1, "b": {"x": 10, "y": 2}}
>>> # Default: Lists extend
>>> base = {"plugins": ["logger", "metrics"]}
>>> override = {"plugins": ["cache"]}
>>> apply_operators(base, override)
{"plugins": ["logger", "metrics", "cache"]}
>>> # Replace operator: explicit override
>>> base = {"model": {"lr": 0.001, "dropout": 0.1}}
>>> override = {"=model": {"lr": 0.01}}
>>> apply_operators(base, override)
{"model": {"lr": 0.01}}
>>> # Remove operator: delete key (idempotent)
>>> base = {"a": 1, "b": 2, "c": 3}
>>> override = {"b": 5, "~c": None}
>>> apply_operators(base, override)
{"a": 1, "b": 5}
Source code in src/sparkwheel/operators.py
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 | |
enable_colors(enabled=None)
Enable or disable color output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool | None
|
True to enable, False to disable, None for auto-detection |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
Current color enable status |
Examples:
>>> enable_colors(False) # Disable colors
False
>>> enable_colors(True) # Force enable colors
True
>>> enable_colors() # Auto-detect
True # (if terminal supports it)
Source code in src/sparkwheel/errors/formatters.py
parse_overrides(args)
Parse CLI argument overrides with automatic type inference.
Supports only key=value syntax with operator prefixes. Types are automatically inferred using ast.literal_eval().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
list[str]
|
List of argument strings to parse (e.g., from argparse) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of parsed key-value pairs with inferred types. |
dict[str, Any]
|
Keys may have operator prefixes (=key for replace, ~key for delete). |
Operators
- key=value - Normal assignment (composes/merges)
- =key=value - Replace operator (completely replaces key)
- ~key - Delete operator (removes key)
Examples:
>>> # Basic overrides (compose/merge)
>>> parse_overrides(["model::lr=0.001", "debug=True"])
{"model::lr": 0.001, "debug": True}
>>> # With operators
>>> parse_overrides(["=model={'_target_': 'ResNet'}", "~old_param"])
{"=model": {'_target_': 'ResNet'}, "~old_param": None}
>>> # Nested paths with operators
>>> parse_overrides(["=optimizer::lr=0.01", "~model::old_param"])
{"=optimizer::lr": 0.01, "~model::old_param": None}
Note
The '=' character serves dual purpose: - In 'key=value' → assignment operator (CLI syntax) - In '=key=value' → replace operator prefix (config operator)
Source code in src/sparkwheel/config.py
validate(config, schema, field_path='', metadata=None, allow_missing=False, strict=True)
Validate configuration against a dataclass schema.
Performs recursive type checking to ensure the configuration matches the structure and types defined in the dataclass schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dictionary to validate |
required |
schema
|
type
|
Dataclass type defining the expected structure |
required |
field_path
|
str
|
Internal parameter for tracking nested field paths |
''
|
metadata
|
Any
|
Optional metadata registry for source locations |
None
|
allow_missing
|
bool
|
If True, allow MISSING sentinel values for partial configs |
False
|
strict
|
bool
|
If True, reject unexpected fields. If False, ignore them. |
True
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails |
TypeError
|
If schema is not a dataclass |
Example
Source code in src/sparkwheel/schema.py
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 | |
validate_operators(config, parent_key='')
Validate operator usage in config tree.
With composition-by-default, validation is simpler: 1. Remove operators always work (idempotent delete) 2. Replace operators work on any type 3. No parent context requirements
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dict to validate |
required |
parent_key
|
str
|
Parent key path (for error messages) |
''
|
Raises:
| Type | Description |
|---|---|
ConfigMergeError
|
If operator usage is invalid |
Source code in src/sparkwheel/operators.py
validator(func)
Decorator to mark a method as a validator.
Validators run after type checking and can validate single fields or relationships between fields. Raise ValueError on failure.
Example
@dataclass class Config: lr: float start: int end: int
@validator
def check_lr(self):
if not (0 < self.lr < 1):
raise ValueError("lr must be between 0 and 1")
@validator
def check_range(self):
if self.end <= self.start:
raise ValueError("end must be > start")