/protean:value-objectfrom protean
Defines Protean value objects: immutable domain elements without identity, defined by attributes. Use for concepts like Money, Email, Address, or Coordinates where only values matter.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Value objects are immutable domain elements that represent descriptive concepts without identity. They are defined entirely by their attribute values: two value objects with the same attributes are considered equal, regardless of instance.
A critical question: does this concept need identity?
Example: Currency note
Key questions:
If identity matters → Use Entity or Aggregate instead. If values matter → Use Value Object.
See Deciding Between Elements for comprehensive guidance.
A value object is defined using the @domain.value_object decorator:
from decimal import Decimal as D
from protean import Domain
from protean.fields import Decimal, String
domain = Domain()
@domain.value_object
class Money:
currency: String(max_length=3, required=True)
amount: Decimal(precision=19, scale=4, required=True, min_value=0)
Use the Decimal field for money, never Float. A float cannot hold most cents exactly. The field stores a standard-library decimal.Decimal, so do arithmetic on money with decimals too. Import the standard-library class under an alias (from decimal import Decimal as D) so it does not clash with the field of the same name.
identifier=True or unique=True@invariant.post (one rule per invariant)@domain.value_object
class Balance:
"""Currency and amount with field-level validations."""
currency: String(max_length=3, min_length=3, required=True) # ISO code
amount: Decimal(precision=19, scale=4, required=True, min_value=0) # No negative amounts
Common field validation parameters:
required, default, unique, choices, validatorsmax_length, min_length, sanitizemin_value, max_valueprecision, scaleUse field validators for single-field data type validations:
from protean.exceptions import ValidationError
class EmailValidator:
def __init__(self):
self.error = "Invalid email address"
def __call__(self, value):
if "@" not in value or value.startswith("@"):
raise ValidationError(self.error)
@domain.value_object
class Email:
address: String(
max_length=254,
required=True,
validators=[EmailValidator()]
)
When to use field validators: For single-field format validations (email format, phone format, etc.). For business rules involving multiple fields, use invariants instead.
@domain.value_object
class Money:
currency: String(max_length=3, required=True)
amount: Decimal(precision=19, scale=4, required=True)
def add(self, other: "Money") -> "Money":
"""Add two Money values, ensuring same currency."""
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
# Return NEW instance (immutability)
return Money(
currency=self.currency,
amount=self.amount + other.amount
)
def multiply(self, factor: int | D) -> "Money":
"""Multiply money by a whole number or a decimal."""
return Money(
currency=self.currency,
amount=self.amount * factor
)
Value objects only support @invariant.post (since they're immutable and created atomically). Invariants run automatically after initialization.
from protean import invariant
@domain.value_object
class DateRange:
start_date: String(required=True)
end_date: String(required=True)
@invariant.post
def end_must_be_after_start(self):
"""End date must not come before start date."""
if self.end_date < self.start_date:
raise ValidationError(
{"date_range": ["End date must be after start date"]}
)
@domain.value_object
class Price:
# Use field-level validation for data type constraints
currency: String(max_length=3, min_length=3, required=True)
amount: Decimal(precision=19, scale=4, required=True, min_value=0) # No negative amounts
@invariant.post
def currency_must_be_valid_ISO_code(self):
"""Currency must be one of the supported ISO codes."""
valid_currencies = ["USD", "EUR", "GBP", "JPY"]
if self.currency not in valid_currencies:
raise ValidationError(
{"currency": [f"Currency must be one of {valid_currencies}"]}
)
Best practices for value object invariants:
amount > 0 → Use Decimal(precision=19, scale=4, min_value=D("0.01")) (field validation), not an invariant. end_date > start_date → Use @invariant.post (cross-field business rule)@domain.aggregate
class Account:
balance = ValueObject(Balance, required=True)
account_number: String(required=True, max_length=20)
@domain.entity(part_of="Order")
class LineItem:
product_id: String(required=True)
quantity: Integer(required=True, min_value=1)
unit_price = ValueObject(Money, required=True)
@property
def line_total(self) -> Money:
"""Calculate line total using Money's multiply method."""
return self.unit_price.multiply(self.quantity)
@domain.value_object
class Address:
street: String(required=True, max_length=100)
city: String(required=True, max_length=50)
@domain.aggregate
class Order:
order_number: String(required=True, identifier=True)
shipping_address = ValueObject(Address, required=True)
billing_address = ValueObject(Address)
total = ValueObject(Money, required=True)
discount = ValueObject(Money) # Optional
Building an aggregate needs an initialized domain and an active domain context.
domain.init(traverse=False)
with domain.domain_context():
account = Account(
balance=Balance(currency="USD", amount=D("100.00")),
account_number="ACC-12345"
)
with domain.domain_context():
# Attribute names: {field_name}_{vo_field_name}
account = Account(
balance_currency="USD",
balance_amount=D("100.00"),
account_number="ACC-12345"
)
Both approaches produce identical results. Attribute initialization works one level deep, on the aggregate or entity that holds the value object, and only when you create it. It does not work for updating a value object later: account.balance_amount = D("5") raises no error, but it sets a stray attribute and leaves account.balance unchanged. A value object's own constructor does not accept flattened attributes either.
Value objects can contain other value objects:
@domain.value_object
class Coordinates:
latitude: Float(required=True, min_value=-90.0, max_value=90.0)
longitude: Float(required=True, min_value=-180.0, max_value=180.0)
@domain.value_object
class Address:
street: String(required=True, max_length=100)
city: String(required=True, max_length=50)
state: String(required=True, max_length=50)
postal_code: String(required=True, max_length=20)
country: String(required=True, max_length=50)
coordinates = ValueObject(Coordinates) # Nested VO
# Pass the nested value object as an object (or as a dict, see below)
address = Address(
street="123 Broadway",
city="New York",
state="NY",
postal_code="10012",
country="USA",
coordinates=Coordinates(latitude=40.7128, longitude=-74.0060)
)
A value object's constructor takes only its own fields. Address(coordinates_latitude=40.7128) fails with "Extra inputs are not permitted". Build the inner value object first and pass it in.
A ValueObject field also takes a plain dict of the inner value object's fields, at any depth: coordinates={"latitude": 40.7128, "longitude": -74.0060}. Protean builds the value object from the dict and validates it the same way, so a dict with a wrong or missing key raises ValidationError.
Value objects cannot be modified after creation:
from protean.exceptions import IncorrectUsageError
balance = Balance(currency="USD", amount=D("100.00"))
try:
balance.currency = "EUR"
except IncorrectUsageError:
print("Value objects are immutable")
try:
balance.amount = D("200.00")
except IncorrectUsageError:
print("Value objects are immutable")
To "change" a value object, replace it entirely:
with domain.domain_context():
account.balance = Balance(currency="USD", amount=D("200.00"))
Methods in value objects must return NEW instances, not modify self:
m1 = Money(currency="USD", amount=D("100.00"))
m2 = Money(currency="USD", amount=D("50.00"))
# add() returns NEW Money instance
m3 = m1.add(m2)
# Originals unchanged
assert m1.amount == D("100.00")
assert m2.amount == D("50.00")
assert m3.amount == D("150.00")
Two value objects with the same attribute values are equal:
bal1 = Balance(currency="USD", amount=D("100.00"))
bal2 = Balance(currency="USD", amount=D("100.00"))
bal3 = Balance(currency="EUR", amount=D("100.00"))
assert bal1 == bal2 # same values
assert bal1 != bal3 # different currency
This is fundamentally different from entities, where identity matters:
account.balance = Balance(currency="USD", amount=D("200.00"))identifier=True or unique=True; registering one raises IncorrectUsageError. A plain Auto() field is accepted, but it generates a new value per instance and breaks equality. Use Entity if you need identity.total = ValueObject(Money) instead of separate total_amount/total_currency fields.See Anti-patterns for detailed examples of each mistake.
check reportscheck inspects your value objects and reports this diagnostic:
VALUE_OBJECT_MUTABLE_FIELD: the value object has a mutable collection field (such as a List), which breaks its value semantics. Replace it with an immutable representation, or move the collection onto the containing entity or aggregate. If the values carry their own identity, model them as an entity.A second diagnostic surfaces at runtime. It depends on the values a value object is built from, so check cannot report it statically:
VALUE_OBJECT_INVARIANT_FAILED: an @invariant.post on the value object did not hold when it was built, so construction raised a ValidationError carrying this code. It is the default code for a failed post-invariant; an invariant declared with @invariant.post(code=...) carries that code instead. Build the value object from values that satisfy its invariants, or catch the ValidationError. The messages on the error are the ones the invariant itself raised, keyed by field.check and resolve what it reportsassets/value_object_in_aggregate.py (opens in a new tab)assets/value_object_in_entity.py (opens in a new tab)assets/value_object_nested.py (opens in a new tab)assets/value_object_simple.py (opens in a new tab)assets/value_object_with_invariants.py (opens in a new tab)assets/value_object_with_methods.py (opens in a new tab)assets/value_object_with_validation.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/equality-and-immutability.md (opens in a new tab)references/in-aggregates.md (opens in a new tab)references/in-entities.md (opens in a new tab)references/nested-value-objects.md (opens in a new tab)references/with-invariants.md (opens in a new tab)references/with-methods.md (opens in a new tab)references/with-validation.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub proteanhq/protean --plugin protean39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar".Other plugins' skills for the same job