Your first model in Python¶
Goal: define a Book model, generate classes.py, and create an
instance of the generated class. This tutorial uses no AI calls.
Install BESSER¶
Use Python 3.11 or 3.12, the versions tested by the project. Create an empty directory for this tutorial and a virtual environment:
python -m venv .venv
Activate it with the command for your shell:
# Windows PowerShell
.\.venv\Scripts\Activate.ps1
# Linux or macOS
source .venv/bin/activate
Then install the library:
python -m pip install besser
To work from an unreleased development build, use the source installation instead.
Define the model and generate code¶
Save this as first_model.py:
"""The complete example used by the Python getting-started tutorial."""
from besser.BUML.metamodel.structural.structural import (
Class,
DomainModel,
IntegerType,
Property,
StringType,
)
from besser.generators.python_classes import PythonGenerator
book = Class(
name="Book",
attributes={
Property(name="title", type=StringType),
Property(name="pages", type=IntegerType),
},
)
library = DomainModel(name="Library", types={book}, associations=set())
PythonGenerator(model=library, output_dir="output").generate()
Property defines an attribute, Class collects the attributes, and
DomainModel collects the classes. PythonGenerator writes an ordinary
Python implementation of the model.
Run the script:
python first_model.py
You should now have output/classes.py containing a Book class with
title and pages properties.
Use the generated class¶
From the same directory, run:
python -c "from output.classes import Book; book = Book(title='Dune', pages=412); print(book.title, book.pages)"
Expected output:
Dune 412
Next steps¶
Choose a generator to produce a database schema or backend.
Structural model example to add authors and relationships.
Structural model for model properties and rules.
Troubleshooting if installation or imports fail.