Grimoire Model
Dict-like model system with schema validation, derived fields, and inheritance for the Grimoire tabletop RPG engine.
Grimoire Model provides a sophisticated, schema-driven model system that combines the familiar dict-like interface with powerful features like automatic field derivation, template-based expressions, model inheritance, and comprehensive validation. Designed to integrate seamlessly with grimoire-context for complete game state management.
✨ Features
- 📚 Dict-like Interface: Familiar Python dictionary operations with schema validation
- ✨ Dual Access Pattern: Support for both dictionary-style (
obj['field']) and attribute-style (obj.field) access - 🔄 Reactive Derived Fields: Automatic computation with dependency tracking and batch updates
- 🧬 Model Inheritance: Multiple inheritance support with automatic namespace-based resolution
- 📝 Template Expressions: Jinja2-powered field templates for dynamic content
- 🎨 Template Engine Compatible: Works seamlessly with Jinja2, Django templates, and other engines
- 🏷️ Namespace Organization: Global model registry with namespace-based organization
- 🛡️ Schema Validation: Pydantic-based type checking and custom validation rules
- 🔧 Dependency Injection: Pluggable resolvers for extensibility
- ⚡ Performance Optimized: Efficient batch updates and lazy evaluation
- 🎯 grimoire-context Integration: Seamless interoperability with context management
🚀 Quick Start
Installation
pip install grimoire-model
Basic Usage
from grimoire_model import ModelDefinition, AttributeDefinition, create_model
# Define a character model schema
character_def = ModelDefinition(
id="character",
name="Player Character",
namespace="rpg", # Organize models in namespaces
attributes={
"name": AttributeDefinition(type="str"),
"level": AttributeDefinition(type="int", default=1),
"hp": AttributeDefinition(type="int", default=100),
"mp": AttributeDefinition(type="int", default=50),
# Derived fields automatically update when dependencies change
"max_hp": AttributeDefinition(
type="int",
derived="{{ level * 8 + hp }}"
),
"character_summary": AttributeDefinition(
type="str",
derived="Level {{ level }} {{ name }} ({{ max_hp }} HP, {{ mp }} MP)"
)
}
)
# Create a character instance
character = create_model(character_def, {
"name": "Aragorn",
"level": 15,
"hp": 120,
"mp": 80
})
# Access data using BOTH dictionary-style AND attribute-style notation
print(character['name']) # "Aragorn" (dictionary-style)
print(character.name) # "Aragorn" (attribute-style)
print(character.max_hp) # 240 (15 * 8 + 120)
print(character.character_summary) # "Level 15 Aragorn (240 HP, 80 MP)"
# Updates work with both access patterns
character['level'] = 20 # Dictionary-style update
character.level = 20 # Attribute-style update (same result)
print(character.max_hp) # 280 (automatically recalculated)
Custom Primitive Types
Register domain-specific primitive types that should be treated as primitive values rather than complex model objects:
from grimoire_model import register_primitive_type, ModelDefinition, AttributeDefinition, create_model_without_validation
# Register custom primitive types
register_primitive_type('roll') # Dice roll notation
register_primitive_type('duration') # Time periods
register_primitive_type('distance') # Measurements
# Define a model using custom primitive types
weapon_def = ModelDefinition(
id='weapon',
name='Weapon',
attributes={
'name': AttributeDefinition(type='str'),
'damage': AttributeDefinition(type='roll') # Custom primitive
}
)
# Create model - custom primitives work like built-in types
weapon = create_model_without_validation(weapon_def, {
'name': 'Longsword',
'damage': '1d8' # Stored as-is, like a string
})
print(weapon['damage']) # '1d8'
Custom primitive types:
- Are stored as raw values without instantiation
- Don't require model registration
- Can have optional validators
- Support domain-specific type semantics
- Work in derived field templates
Global Model Registry
Models are automatically registered in a global registry using namespaces:
from grimoire_model import get_model
# Models auto-register when created
character_def = ModelDefinition(
id="character",
namespace="rpg", # Registered in "rpg" namespace
# ... attributes ...
)
# Retrieve from anywhere in your application
retrieved_def = get_model("rpg", "character")
new_character = create_model(retrieved_def, {"name": "Hero"})
# Perfect for inheritance - child models automatically find parents
base_def = ModelDefinition(id="base", namespace="rpg", ...)
child_def = ModelDefinition(id="child", namespace="rpg", extends=["base"], ...)
# No manual registry needed - inheritance resolves automatically!
Model Inheritance with Namespaces
from grimoire_model import get_model, clear_registry
# Base entity definition (auto-registered in namespace)
base_entity_def = ModelDefinition(
id="base_entity",
name="Base Entity",
namespace="game", # Registered in "game" namespace
attributes={
"id": AttributeDefinition(type="str"),
"name": AttributeDefinition(type="str"),
"description": AttributeDefinition(type="str", default="")
}
)
# Character extends base entity (automatic inheritance resolution)
character_def = ModelDefinition(
id="character",
name="Character",
namespace="game", # Same namespace enables automatic inheritance
extends=["base_entity"], # Automatically finds base_entity in namespace
attributes={
"level": AttributeDefinition(type="int", default=1),
"hp": AttributeDefinition(type="int", default=100),
"max_hp": AttributeDefinition(
type="int",
derived="{{ level * 8 + hp }}"
)
}
)
# Create character with inherited fields (no registry needed!)
character = create_model(
character_def,
{
"id": "char_001", # From base_entity
"name": "Legolas", # From base_entity
"description": "Elf archer", # From base_entity
"level": 12, # From character
"hp": 96 # From character
}
)
print(character['id']) # "char_001" (inherited)
print(character['name']) # "Legolas" (inherited)
print(character['max_hp']) # 192 (derived field)
# Retrieve models from global registry
retrieved_char_def = get_model("game", "character")
another_character = create_model(retrieved_char_def, {
"id": "char_002",
"name": "Gimli"
})
Integration with grimoire-context
from grimoire_context import GrimoireContext
# Create context with character model
context = GrimoireContext({
'party': {
'leader': character,
'members': 4
}
})
# Modify character through context - derived fields update automatically
context = context.set_variable('party.leader.level', 25)
updated_character = context.get_variable('party.leader')
print(updated_character['level']) # 25
print(updated_character['max_hp']) # 296 (automatically recalculated)
Batch Updates for Performance
# Batch multiple changes for better performance
character.batch_update({
'level': 30,
'hp': 150,
'mp': 120
})
# All derived fields updated once after batch completion
print(character['max_hp']) # 390 (30 * 8 + 150)
Template Engine Integration
GrimoireModel objects support both dictionary-style and attribute-style access, making them fully compatible with template engines like Jinja2, Django templates, and others:
from jinja2 import Template
# Create a weapon model
weapon_def = ModelDefinition(
id="weapon",
name="Weapon",
attributes={
"name": AttributeDefinition(type="str"),
"damage": AttributeDefinition(type="str"),
"bonus": AttributeDefinition(type="int", default=0),
}
)
weapon = create_model(weapon_def, {
"name": "Longsword",
"damage": "1d8",
"bonus": 2
})
# Use attribute access in Jinja2 templates
template = Template("{{ weapon.name }}: {{ weapon.damage }} +{{ weapon.bonus }}")
result = template.render(weapon=weapon)
print(result) # "Longsword: 1d8 +2"
# Works with more complex templates
template = Template("""
{% if weapon.bonus > 0 %}
{{ weapon.name }} ({{ weapon.damage }}+{{ weapon.bonus }})
{% else %}
{{ weapon.name }} ({{ weapon.damage }})
{% endif %}
""")
This dual-access pattern (dictionary and attribute) provides:
- Template Compatibility: Works seamlessly with Jinja2, Django, and other template engines
- Standard Python Behavior: Objects behave like normal Python objects
- IDE Support: Better autocomplete and type hints
- Backward Compatible: All existing dictionary-style code continues to work
📚 Documentation
- Logging Configuration - Configure library logging output and integration
📚 Core Concepts
Model Definitions
Model definitions are schemas that describe the structure, types, and behavior of your data:
model_def = ModelDefinition(
id="weapon",
name="Weapon",
namespace="combat", # Organize in combat namespace
description="Combat weapon with damage calculations",
attributes={
"name": AttributeDefinition(type="str"),
"base_damage": AttributeDefinition(type="int", default=1, range="1..50"),
"enhancement": AttributeDefinition(type="int", default=0, range="0..10"),
# Derived field with complex logic
"total_damage": AttributeDefinition(
type="int",
derived="{{ base_damage + enhancement * 2 }}"
),
"damage_category": AttributeDefinition(
type="str",
derived="{% if total_damage >= 20 %}High{% elif total_damage >= 10 %}Medium{% else %}Low{% endif %}"
)
},
validations=[
ValidationRule(
expression="base_damage > 0",
message="Base damage must be positive"
)
]
)
Template Expressions
Use Jinja2 templates for powerful derived field logic:
# Simple expression
"max_hp": "{{ level * 8 + constitution * 2 }}"
# Conditional logic
"damage_bonus": "{% if strength >= 15 %}{{ (strength - 10) // 2 }}{% else %}0{% endif %}"
# Complex calculations
"skill_modifier": "{{ (skill_level + attribute_bonus - 10) // 2 }}"
Validation Rules
Add custom validation logic to ensure data integrity:
ValidationRule(
expression="level >= 1 and level <= 100",
message="Character level must be between 1 and 100"
),
ValidationRule(
expression="hp > 0 or status == 'dead'",
message="Living characters must have positive HP"
)
A rule has only expression and message. There is no severity (every rule
is an error) and no fields.
Writing and reading data
- A write is a transaction: it validates the value, recomputes dependents,
checks every derived field it recomputed against its own constraints and the
model-level
validations, and rolls back on failure. - Reads return copies:
model["g"]is a fresh dict/list and a nested model is an independent copy. Write through a dotted path (model["hit_points.current"] = 5) or a whole value; mutating what you read does not change the model. - Derived attributes are not writable.
del model[key]unsets an optional attribute and raises for a required, readonly or derived one. - Definitions are closed: an unknown key (
optinal: true) is an error. Undeclared data keys are errors too. extendsresolves later-parent-wins:extends: [a, b]meansboverridesa, then the model's own attributes override both.type: list, of: itembuilds each element as anitemmodel; atype: dictattribute has no declared interior and holds free-form data.- A value typed as a model — an attribute or an
ofelement — also accepts a model that extends it: aweaponmodel (extends: [item]) is anitem, and keeps its own attributes. A plain dict has no type of its own and is always built as the declared model.model.is_a("item")answers the same question. - An instance of a model that extends another records its model id in its data
as
_model(read-only), so a weapon saved as plain data in anof: itemlist is rebuilt as a weapon. A dict tagged_model: weaponis built as a weapon where anitemis declared; untagged, it is built as the declared model. Attribute names beginning with_are reserved.
🔧 API Reference
Core Classes
ModelDefinition
ModelDefinition(
id: str, # Unique model identifier
name: str, # Human-readable name
namespace: str = "default", # Namespace for organization and inheritance
description: str = "", # Model description
attributes: Dict[str, AttributeDefinition], # Field definitions
extends: List[str] = None, # Parent model IDs (resolved in namespace)
validations: List[ValidationRule] = None, # Validation rules
ancestors: List[str] = None, # Recorded by resolve_model_inheritance
)
AttributeDefinition
AttributeDefinition(
type: str, # Data type (str, int, float, bool, list, dict, or custom primitive)
optional: bool = False, # May be left without a value; required unless True
default: Any = None, # Default value
derived: str = None, # Template expression for derived fields
range: str = None, # Value range constraint (e.g., "1..100")
enum: List[str] = None, # Allowed values
pattern: str = None, # Regex pattern for strings (a full match)
of: str = None, # Element type for a list attribute
description: str = "" # Field description
)
GrimoireModel
class GrimoireModel(MutableMapping):
def __init__(
self,
model_definition: ModelDefinition,
data: Dict[str, Any] = None,
template_resolver: TemplateResolver = None,
derived_field_resolver: DerivedFieldResolver = None,
instance_id: str = None,
skip_initial_validation: bool = False,
registry: ModelRegistry = None,
)
# Dict-like interface
def __getitem__(self, key: str) -> Any # a container is returned as a copy
def __setitem__(self, key: str, value: Any) -> None
def __delitem__(self, key: str) -> None
def __iter__(self) -> Iterator[str]
def __len__(self) -> int
def keys(), values(), items()
# Attribute-style access
def __getattr__(self, name: str) -> Any
def __setattr__(self, name: str, value: Any) -> None
# Enables: obj.field_name (read) and obj.field_name = value (write)
# Batch operations
def batch_update(self, updates: Dict[str, Any]) -> None
# Dot-notation read
def get(self, path: str, default: Any = None) -> Any
# Write a nested leaf with a dotted key:
model["hit_points.current"] = 5
# Derived-field introspection
def get_derived_fields() -> Set[str]
def get_field_dependencies(field_name: str) -> Set[str]
def get_dependent_fields(field_name: str) -> Set[str]
def validate() -> List[str]
def is_a(model_id: str) -> bool # this model, or one it inherits from
There is no set, has or delete method; use model[key] = value,
key in model and del model[key].
Factory Functions
create_model
def create_model(
model_definition: ModelDefinition,
data: Dict[str, Any] = None,
template_resolver_type: str = "jinja2",
template_resolver: TemplateResolver = None,
derived_field_resolver: DerivedFieldResolver = None,
instance_id: str = None,
skip_initial_validation: bool = False,
template_resolver_kwargs: Dict[str, Any] = None,
derived_resolver_kwargs: Dict[str, Any] = None,
registry: ModelRegistry = None,
) -> GrimoireModel
create_model_without_validation takes the same arguments (it always skips
initial validation). There is no derived_field_resolver_type argument; pass
derived_resolver_kwargs={"batched": True} for a batched resolver. Inheritance
and model-typed attributes resolve in the model's own namespace first, falling
back to another namespace only when exactly one has the id; pass registry= to
use a registry other than the global one.
Global Registry Functions
from grimoire_model import register_model, get_model, clear_registry
# Register model manually (usually automatic)
register_model("my_namespace", model_definition)
# Retrieve model from registry
model_def = get_model("my_namespace", "my_model")
# Clear all models (useful for testing)
clear_registry()
# Access registry directly for advanced operations
from grimoire_model import get_model_registry
registry = get_model_registry()
registry_dict = registry.get_registry_dict()
all_namespaces = registry.list_namespaces()
Primitive Type Registry Functions
from grimoire_model import (
register_primitive_type,
unregister_primitive_type,
is_primitive_type,
clear_primitive_registry
)
# Register a custom primitive type
register_primitive_type('roll')
# Register with optional validator
def validate_duration(value):
if isinstance(value, str) and value.endswith('s'):
return True, None
return False, "Duration must end with 's'"
register_primitive_type('duration', validator=validate_duration)
# Check if a type is registered as primitive
is_primitive_type('roll') # True
is_primitive_type('unknown') # False
# Unregister a primitive type
unregister_primitive_type('roll')
# Clear all registered primitives (useful for testing)
clear_primitive_registry()
Template Resolvers
Jinja2TemplateResolver: Standard Jinja2 template syntaxCachingTemplateResolver: Cached template compilation for performance
Derived Field Resolvers
BatchedDerivedFieldResolver: Batches updates for performanceDerivedFieldResolver: Immediate update resolver
Expression reference paths
grimoire_model.resolvers.template.extract_reference_paths(expression) parses
a Jinja2 expression and returns every maximal dotted reference path, e.g.
"{{ p.mod + 1 }}" → {"p.mod"}. Derived-field dependency tracking uses it.
🧪 Development
Setup
git clone https://github.com/wyrdbound/grimoire-model.git
cd grimoire-model
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -e ".[dev]"
Running Tests
# Run all tests with coverage
uv run python -m pytest --cov=grimoire_model --cov-report=term
# Run specific test file
uv run python -m pytest tests/test_model.py
# Run with verbose output
uv run python -m pytest -v
# Generate HTML coverage report
uv run python -m pytest --cov=grimoire_model --cov-report=html
# Open htmlcov/index.html in browser
Note: Use the virtual environment in the project root as specified in the development guidelines.
Code Quality
# Install development dependencies
source .venv/bin/activate && pip install ruff mypy
# Linting and formatting
source .venv/bin/activate && ruff check .
source .venv/bin/activate && ruff format .
# Type checking
source .venv/bin/activate && mypy src/grimoire_model/
# Run all quality checks
source .venv/bin/activate && ruff check . && mypy src/grimoire_model/
Running Examples
# Basic usage example
source .venv/bin/activate && python examples/01_basic_usage.py
# Advanced features and inheritance
source .venv/bin/activate && python examples/02_advanced_usage.py
# Inheritance and polymorphism
source .venv/bin/activate && python examples/03_inheritance_polymorphism.py
# Performance and integration testing
source .venv/bin/activate && python examples/04_performance_integration.py
📋 Requirements
- Python 3.10+
- pydantic >= 2.0.0
- pyrsistent >= 0.19.0
- jinja2 >= 3.1.0
- grimoire-logging >= 0.1.0
Development Dependencies
- pytest >= 7.0.0
- pytest-cov >= 4.0.0
- pytest-mock >= 3.0.0
- hypothesis >= 6.0.0
- mypy >= 1.0.0
- ruff >= 0.1.0
🎯 Use Cases
Grimoire Model excels in scenarios requiring structured, validated data with complex relationships:
- RPG Character Systems: Stats, levels, equipment with derived values
- Game Item Management: Equipment, inventory, crafting systems
- Rule Engine Data: Complex game mechanics with interdependent calculations
- Configuration Systems: Hierarchical configs with inheritance and validation
- Dynamic Content: Template-based content generation with context awareness
🏗️ Architecture
The package follows clean architecture principles with clear separation of concerns:
- Core Layer: Model definitions, schemas, and the main GrimoireModel class
- Resolver Layer: Pluggable template and derived field resolution systems
- Validation Layer: Type checking, constraints, and custom validation rules
- Utils Layer: Inheritance resolution, path utilities, and helper functions
- Integration Layer: grimoire-context compatibility and factory functions
Key Design Principles
- Dependency Injection: All major components can be swapped via constructor injection
- Private Storage: Storage is copy-on-write; reads return copies, so a write through a value read earlier does not reach the model
- Template-Driven: Jinja2 templates provide powerful expression capabilities
- Performance-Focused: Batch updates and lazy evaluation minimize overhead
- Type Safety: Full type hints and Pydantic integration for runtime validation
- Explicit Errors: Prefers explicit errors over fallbacks to maintain system stability
📈 Performance
Current benchmarks (86% test coverage, 184 tests passing):
- Model Creation: ~1ms for simple models, ~5ms for complex inheritance
- Field Updates: ~0.1ms for direct fields, ~2ms for derived field cascades
- Batch Updates: 50-80% faster than individual updates for multiple fields
- Memory Usage: ~50KB per model instance (excluding data)
- Template Resolution: Cached compilation provides 10x speed improvement
🔄 Integration with grimoire-context
Seamless integration is automatically enabled when both packages are installed:
from grimoire_model import create_model, ModelDefinition, AttributeDefinition
from grimoire_context import GrimoireContext
# Models work naturally in contexts
character = create_model(character_def, character_data)
context = GrimoireContext({'player': character})
# Context operations automatically handle model updates
updated_context = context.set_variable('player.level', 25)
updated_character = updated_context['player']
# Derived fields update automatically
print(updated_character['max_hp']) # Recalculated based on new level
🚨 Error Handling
The package provides a comprehensive exception hierarchy:
from grimoire_model import (
GrimoireModelError, # Base exception
ModelValidationError, # Validation failures
TemplateResolutionError, # Template processing errors
InheritanceError, # Model inheritance issues
DependencyError, # Derived field dependency issues
ConfigurationError # Setup and configuration errors
)
try:
character = create_model(character_def, invalid_data)
except ModelValidationError as e:
print(f"Validation failed: {e}")
print(f"Field: {e.field_name}")
print(f"Value: {e.field_value}")
print(f"Validation rule: {e.validation_rule}")
🔍 Advanced Features
Custom Template Resolvers
from grimoire_model.resolvers.template import TemplateResolver
class CustomTemplateResolver(TemplateResolver):
def resolve_template(self, template: str, context: dict) -> str:
# Custom template logic
return processed_template
# Use custom resolver
model = GrimoireModel(
model_def,
data,
template_resolver=CustomTemplateResolver()
)
Custom Validators
A field validator is a FieldValidator subclass returned by get_name(); a
custom primitive type instead takes a (value) -> (is_valid, message) callable:
from grimoire_model import register_primitive_type
def validate_duration(value):
if isinstance(value, str) and value.endswith("s"):
return True, None
return False, "Duration must end with 's'"
register_primitive_type("duration", validator=validate_duration)
Multiple Inheritance
# Multiple parent models (all in same namespace)
combat_def = ModelDefinition(
id="character",
namespace="game", # All parent models must be in same namespace
extends=["base_entity", "combatant", "spell_caster"],
attributes={...}
)
# Automatic conflict resolution with left-to-right precedence
# Parents automatically resolved from "game" namespace
📄 License
This project is licensed under the MIT License. See the LICENSE file for complete terms and conditions.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
If you have questions about the project, please contact: wyrdbound@proton.me
Copyright (c) 2025 The Wyrd One
Metadata
Release files for grimoire-model 0.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| grimoire_model-0.9.0.tar.gz | 128.8 kB | Without provenance | Details for grimoire_model-0.9.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| grimoire_model-0.9.0-py3-none-any.whl | Python 3 | none | any | Details for grimoire_model-0.9.0-py3-none-any.whl |
Total release size: 196.3 kB
Release files / grimoire_model-0.9.0.tar.gz
| Download URL | grimoire_model-0.9.0.tar.gz |
|---|---|
| Size | 128.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a518e72b930f5b1b6eb430e6c51110acca1bc2722afd66e772b6e70a7f8b8cce
|
|
BLAKE2b-256 checksum How to use checksums |
c270996cd4b13f1c53b5a017c93e8875fd434bf5c1fc3fe5997a62ad7449ce38
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.16
|
Release files / grimoire_model-0.9.0-py3-none-any.whl
| Download URL | grimoire_model-0.9.0-py3-none-any.whl |
|---|---|
| Size | 67.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8c747a5dc32c56c737d06d35293202454822387cd443e50b10d814d2fc10be7d
|
|
BLAKE2b-256 checksum How to use checksums |
7d23360d37fd61e1955dc7d6a00e238ffc8113815e7ac714d1c3a4582506637a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.16
|
Security for grimoire-model 0.9.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.