YORM (YAML Object-Relational Mapper)
YORM (YAML Object-Relational Mapper) is a Python library that provides automatic object-YAML mapping, allowing Python objects to be seamlessly persisted to and loaded from YAML files. It enables defining models with attributes that are automatically synchronized with a specified YAML file, supporting features like autosaving and schema validation. The current version is 1.6.2, and it has an active but irregular release cadence.
Common errors
-
AttributeError: 'MyModel' object has no attribute 'some_field'
cause An attribute was accessed or assigned on a YORM model object that was not explicitly defined using `yorm.attr()` in the class definition.fixEnsure all attributes you intend to use with the model are defined using `yorm.attr`, for example: `some_field = yorm.attr(type=str)`. -
FileNotFoundError: [Errno 2] No such file or directory: '/path/to/nonexistent/file.yaml'
cause YORM attempted to load or create a YAML file at a path where the parent directories do not exist.fixEnsure that the parent directories for the YAML file path provided to `yorm.sync()` exist. YORM will create the file itself, but not intermediate directories. You can create them with `os.makedirs(os.path.dirname(file_path), exist_ok=True)`. -
yorm.exceptions.InvalidObjectError: Expected value of type <class 'str'>, got 123
cause Data loaded from the YAML file or assigned to an attribute does not match the `type` specified in its `yorm.attr()` definition.fixEnsure that data in the YAML file conforms to the expected types defined in your YORM model, or that values assigned to attributes during runtime match their specified types.
Warnings
- deprecated Calling `yorm.sync()` without a `path` argument is deprecated and will raise a `DeprecationWarning`.
- gotcha If `autosave=False` is set (or omitted) on a model, changes to objects will not be automatically persisted to the YAML file. Data loss can occur if `model.save()` is not explicitly called.
- gotcha Manually editing the generated YAML file in an incorrect format can lead to `ruamel.yaml` parsing errors or `yorm.exceptions.InvalidObjectError` when the data is loaded.
Install
-
pip install yorm
Imports
- Model
import yorm class MyModel(yorm.Model):
- attr
import yorm @yorm.attr(autosave=True) class MyModel(yorm.Model):
- sync
yorm.sync(MyModel)
import yorm yorm.sync(MyModel, 'path/to/data.yaml')
Quickstart
import yorm
import os
import tempfile
import shutil
# Create a temporary directory for the YAML file
temp_dir = tempfile.mkdtemp()
try:
# Define a model with autosave enabled at the class level
@yorm.attr(autosave=True)
class Person(yorm.Model):
name = yorm.attr(type=str)
email = yorm.attr(type=str, default='')
# Synchronize the model with a YAML file in the temporary directory
file_path = os.path.join(temp_dir, 'person.yaml')
yorm.sync(Person, file_path)
print(f"Synchronized Person model with: {file_path}")
# Create a new person object. Due to autosave=True, it's saved automatically.
print("\nCreating Bob...")
bob = Person(name="Bob", email="bob@example.com")
print(f"Bob created: {bob.name} ({bob.email})")
# Update an attribute. The change is saved automatically.
print("Updating Bob's email...")
bob.email = "robert@example.com"
print(f"Bob's email updated to: {bob.email}")
# Fetch all persons (should be just Bob)
print("\nFetching all persons...")
persons = Person.all()
for p in persons:
print(f"Found: {p.name} ({p.email})")
# Verify the update by reloading and checking
if persons and persons[0].email == "robert@example.com":
print("Update verified: Bob's email is now robert@example.com")
else:
print("Error: Bob's email not updated as expected.")
# Delete all persons. This also gets persisted.
print("\nDeleting all persons...")
Person.all().clear()
print(f"Persons remaining after clear: {len(Person.all())}")
finally:
# Clean up the temporary directory
shutil.rmtree(temp_dir)
print(f"\nCleaned up temporary directory: {temp_dir}")