Skip to content

Latest commit

 

History

History
276 lines (219 loc) · 19.2 KB

python.md

File metadata and controls

276 lines (219 loc) · 19.2 KB

Python language mapping

How the rules of the portable contract appear in the generated Python API. Rule ids (T1, C2, ...) refer to the contract.

Claimed modules: core, views, events, history, reflection, equality-modes, json, validation, collections, externals, behavior, traversal. Python supports custom __eq__ and __hash__, so Python follows N2 (equality-modes) alongside Java and C# (see Equality).

Generating

The Gradle plugin generates Python with vmf { targets = ['python'] } (into build/generated-src/vmf-main-python), the Maven plugin with <targets><target>python</target></targets> (into target/generated-sources/python-vmf); from code, VMF.generate(GenerationTarget.PYTHON, outputDir, sourceFiles...) does the same. Each model namespace becomes one model.py under a PEP 420 namespace package directory (eu/mihosoft/vmf/portable/tree/model.py) that exports the model classes, ReadOnly<Name> protocols, optional host-binding helpers, and a ModelSnapshot class for documents and traversal.

Generated code targets Python 3.10+ (from __future__ import annotations, PEP 604 X | Y unions) and depends only on the zero-dependency mihosoft-vmf-runtime package (python-runtime/, imported as vmf_runtime). Install the matching version from PyPI (pip install mihosoft-vmf-runtime==<version>), or pack a local PEP 427 pure-Python wheel with ./gradlew :vmf:packPythonRuntime into core/build/target-runtimes/mihosoft_vmf_runtime-<pep440-version>-py3-none-any.whl (includes py.typed for mypy/pyright; see Releasing VMF).

Generated code and runtime belong to one VMF version. The generated classes call internal helpers of vmf_runtime that change between versions: after updating VMF, generate the models again and use the matching runtime version.

Types and values (T)

Model Python
model type X class X (PascalCase)
create an object X() or keyword arguments X(name="a", children=[c])
@InterfaceOnly type abstract class whose __new__ rejects direct instantiation (TypeError); isinstance works via inheritance and vmf.declare_supertypes fallback
several supertypes maximal C3-compatible Python multiple inheritance; any remaining supertypes are registered with vmf.declare_supertypes (vmf.is_instance / isinstance via ABCMeta)
property declared again (T7) one property; a narrowed getter or containment end on an @InterfaceOnly supertype is an @abstractmethod property there, implemented by each subtype
generic type (T8) class Series(ABC, Generic[_T_Series_T]); a Number bound becomes bound=Union[int, float], a model bound bound="Entry"; concrete subtypes bind the arguments (class Temperatures(NumericSeries[float])) and check values at runtime
property firstName PEP 8 snake_case property first_name (Python keywords escaped with a trailing _, e.g. from_, class_)
byte, short, int, long int with strict runtime type (bool rejected) and signed 8/16/32/64-bit range checks (ValueError/TypeError) (T4, T6)
float, double float (int widened, bool rejected); float rounds to IEEE-754 binary32 precision via struct.pack/unpack (T6)
boolean bool (exact bool; int is rejected)
char str of length 1 within UTF-16 BMP (0x0000..0xFFFF); default "\u0000"
String and optional values `str
list property (T[]) vmf.ScalarList[T], vmf.ContainmentList[TOwner, TChild], or vmf.ReferenceList[T] with add, add_all, insert, set, remove, remove_at, clear, at, index_of, contains, count, len(...), indexing, and iteration
@DefaultValue initial value or collection content of new objects (see Defaults)
external type see External types

External types (X)

An @ExternalType stub names a type of the host language. For Python, @Annotation(key = "vmf:python:external-type", value = ...) on the stub names the Python type:

Stub Python
value = "\"LOW\" | \"HIGH\"", a union of string literals (for Java enums) exported Level: TypeAlias = Literal["LOW", "HIGH"]; setters and documents enforce the allowed literal names (X1)
value = "object" (or a builtin name) that global Python type
value = "Distance" and vmf:python:external-module = "hosts.externals" from hosts.externals import Distance emitted under if TYPE_CHECKING:; a name taken by a generated class is imported as HostDistance
java.util.UUID, no annotation str in canonical lowercase 8-4-4-4-12 UUID form (X3); setters accept either case and reject malformed strings
java.lang.Object, no annotation Any holding an untyped JSON value (X4)

External types can be single values, lists (ScalarList), and delegated method parameters or results.

Untyped JSON values are None, str, bool, int, finite float, list, and dict with str keys, without cycles and nested at most 1,000 deep. Python preserves arbitrary-precision integers and distinguishes int from float and bool natively. Content equality compares untyped values structurally as JSON values regardless of dict key order; deep copies share them.

Other external types need a codec when they occur in documents — a vmf.ExternalCodec[T] supplied through host bindings:

import vmf_runtime as vmf
from example.model import install_model_bindings

install_model_bindings({
    "externals": {
        "Distance": vmf.ExternalCodec(
            write=lambda d: {"meters": d.meters},
            read=lambda data: Distance(data["meters"]),
            equals=lambda a, b: a.meters == b.meters,   # optional, default ==
            hash_code=lambda d: int(d.meters),           # optional, agrees with equals
        ),
    },
})

write returns a non-None JSON value and read reconstructs the host value from it (X5). Content equality delegates to equals and hash_code (X6); deep copies and read-only views share external values.

Host bindings

A model that needs host code (codecs for external types, bound defaults, or delegated behaviors) exports a ModelBindings Protocol and install_model_bindings(bindings). Callers may pass either an object implementing ModelBindings (such as a SimpleNamespace or custom class) or a nested dict / Mapping.

install_model_bindings validates eagerly that every required binding is present and raises TypeError listing any missing keys. Model code fetches each binding lazily on first use: before install_model_bindings runs, reaching a binding raises RuntimeError naming the missing binding and install_model_bindings. Calling install_model_bindings again replaces bindings for subsequent documents, new objects, and first behavior calls, while existing objects retain behaviors they already instantiated. Models needing no host code generate neither ModelBindings nor install_model_bindings.

Defaults

@DefaultValue Python
a literal the initial value
a constant of an enum mapped to a literal union (Level.MEDIUM) the literal ("MEDIUM"), no binding needed
java.util.List.of(...), Set.of(v), Map.of(k, v) of literals on an ordered set, bounded list, set, or map (K12) initial collection content
java.util.List.of(T.newInstance()), or a builder setting one String property, on a set of model objects without opposite (K12) a new T(...) per owner instance
any other expression, with @Annotation(key = "vmf:python:bind-default", value = "true") bindings.defaults.<Type>.<property_snake_case>(), called once per new object

Defaults of mutable objects are applied in __init__ after the construction hook (B3) and before keyword initializer arguments; a collection default replaces anything the hook added. @Immutable types apply defaults for any omitted (vmf.UNSET) constructor keyword argument. A nullable property currently holding None when its default is non-None is serialized as explicit null in documents so readers preserve None (J1). Collections with defaults are written even when empty (K12).

Behavior (B)

@DelegateTo methods become methods on the generated Python class that forward to a per-object behavior with self (caller) as the first argument. Each type declaring delegated methods or a construction hook gets a <Type>Behavior(Protocol), and bindings.behaviors.<Type> supplies the factory:

class CounterBehavior(Protocol):
    def on_counter_instantiated(self, caller: Counter) -> None: ...
    def add(self, caller: Counter, amount: int) -> int: ...

install_model_bindings({"behaviors": {"Counter": DefaultCounter}})
counter.add(2)                             # DefaultCounter().add(counter, 2)
counter.replace_behavior(TestCounter())    # only this object
Rule Python
a call (B1) x.add(2) calls behavior.add(x, 2) and returns its result
default behavior (B2) created lazily per object and declaring type from bindings.behaviors.<Type>()
construction hook (B3) on_<type_snake_case>_instantiated(self, caller) runs in __init__ (including deep copies and deserialized objects) before defaults; at most one hook runs per object; immutable objects have none
replacement (B4) x.replace_behavior(b): validates that b provides callable methods for every delegated method of x's class (else TypeError), does not run the hook, and is not copied by deep_copy()
inherited methods (B5) subtypes inherit the declaring type's behavior unless they rebind the method; interface-only methods without a binding raise RuntimeError unless replaced
delegated toString() emitted as __str__(self) -> str on the model class and calls behavior.to_string(self) on the behavior object

Delegated method names and parameter names follow PEP 8 snake_case. Overloaded methods must differ in parameter count and are emitted with @overload typing stubs plus runtime arity dispatch. Variable-argument parameters map to *args on the model method and a tuple argument on the behavior method. Static methods, checked exceptions, and Object methods other than toString() are rejected.

Collections (K)

Model Python
Set<T> of scalars vmf.ScalarSet[T] with add, add_all, remove, clear, contains, count, to_list, len(...), in, and iteration
@Multiplicity(kind = ORDERED_SET) list ScalarList or ReferenceList with unique=True: add returns False for an already present element; insert and set reject duplicates
@Multiplicity(upper = n) list of scalars ScalarList rejecting None and edits exceeding n (ValueError); add_all performs a single atomic edit
VMap<K, V> vmf.ScalarMap[K, V | None]: put(key, value) (insert/replace in place, returns previous value or None), add(key, value) (rejects existing key), put_all(entries), get(key), has(key), remove(key), clear(), count, keys(), values(), entries(), to_dict(), len(...), in, and insertion-order (key, value) iteration
Set<T> of model objects vmf.ReferenceSet[T] (also with opposite); @Contains Set<T> is vmf.ContainmentSet[TOwner, TChild]
@Contains @Keyed(by = "sku") keyed ContainmentList or ContainmentSet, plus owner.find_items_by_sku(key) -> Item | None on both the mutable object and its read-only view
in a read-only view or @Immutable type vmf.ReadOnlyList[T], vmf.ReadOnlySet[T], vmf.ReadOnlyMap[K, V]
@DefaultValue of a collection (K12) applied in __init__ after the construction hook; immutable classes accept any Iterable (or Mapping/pair iterable for maps)

Containment and references (C, R)

Setting a containment property or adding to a containment collection moves the child out of any previous owner and updates its @Container property. Opposite references stay synchronized from either side. Any rejected edit raises an exception (TypeError or ValueError) and leaves the model unchanged.

Use the with vmf.edit(origin): context manager to group multiple edits into an atomic transaction that rolls back if an exception is raised inside the block.

Equality and copies (Q, N)

Rule Python
content equality (Q1) x.content_equals(y), x.content_hash_code()
deep copy (Q3) x.deep_copy()
language equality (N2) __eq__ and __hash__ follow the declared @VMFEquals / @VMFModel(equality = ...) mode

Without @VMFEquals or @VMFModel(equality = ...), __eq__ and __hash__ use object identity (INSTANCE). With CONTAINMENT_AND_EXTERNAL or ALL, the generated class overrides __eq__ and __hash__ via vmf.model_equals and vmf.model_hash_code (handling cycles safely and matching Java/C# equality modes). As in Python generally, objects with structural equality should not be mutated while stored as dict keys or set elements. Use is for identity comparison regardless of equality mode.

Views (V)

x.as_read_only() returns a live vmf.ReadOnlyView proxy typed by the generated ReadOnly<Name> Protocol. Assigning or deleting attributes on a read-only view raises AttributeError / TypeError, collections expose read-only views whose model elements are wrapped as read-only views, and view.vmf_changes permits listener registration only (no recording).

@Immutable types accept all values via keyword arguments in __init__ (e.g. Label(name="n", title="t")) and reject __setattr__ / __delattr__ with AttributeError. Their collections are ReadOnlyList, ReadOnlySet, or ReadOnlyMap. An immutable object is its own read-only view and is shared by deep_copy().

Events and history (E, H)

Rule Python
listen unsub = x.vmf_changes.add_listener(callback, "local") (or "recursive", default); calling unsub() removes the listener
a change vmf.ModelChange (source, property, kind, old_value, new_value, values, replaced, indices, keys) with kind in ("set", "add", "remove", "replace")
record x.vmf_changes.start(), x.vmf_changes.stop(); x.vmf_changes.history holds one vmf.ModelEdit per edit
undo, redo entry.undo(), entry.redo()

Local and recursive listeners on the same object fire in registration order (E7). Delivery proceeds from the changed object to its nearest container ancestor upward regardless of registration order (E8). Reentrant edits inside a listener are delivered immediately (E9) and recorded after the triggering edit so full undo restores the starting state (H4).

Reflection (F)

x.vmf_type returns a vmf.ModelType with name, immutable, properties (tuple of vmf.ModelProperty in VMF property order, F1), annotations (tuple of vmf.ModelAnnotation key/value pairs including both user annotations F2 and reserved vmf:* metadata F3, including vmf:wire:type, vmf:wire:name, and vmf:wire:*:<format>), and property(name). Each ModelProperty exposes its logical VMF name, Python member_name, and annotations. See Stable IDs, wire names, and reflection.

Documents (J)

Document Python
with @Id / @vmf-id and @vmf-type ModelSnapshot.write(x), ModelSnapshot.read(json_text, X)
plain (J5) ModelSnapshot.write_plain(x, X), ModelSnapshot.read_plain(json_text, X)
plain, references left out ModelSnapshot.write_plain(x, X, "omit")

Mutable types declaring @Id (str or canonical UUID) serialize their declared @Id value as the reference target ID and omit synthetic @vmf-id (J7). @WireName JSON overrides (format = WireName.JSON) and default @WireName names are applied automatically. Strict JSON parsing rejects duplicate keys, trailing garbage, and non-canonical numbers, and round-trips full 64-bit signed integers exactly. References to immutable values are serialized inline by value in every mode.

Validation (L)

Rule Python
validate x.validate() returns a tuple[vmf.ValidationIssue, ...] for x and its contained subtree; an empty tuple means valid
an issue vmf.ValidationIssue(code, path, message, model_code, model_path, severity)
contract code and path (L7) model_code ("vmf.range") and model_path ("/segments/0/start")
Python code and path code ("range") and path using Python member names ("segments[0].start")

@Range checks exact integers for integer types (including 64-bit long) and exact IEEE-754 bounds for float/double. @Length counts Unicode code points (len(s) in Python 3). Portable @Pattern compiles with re anchored appropriately and matches anywhere in the string (L5). A Java-only pattern (@Pattern(value = "...", portable = false)) requires one @Annotation(key = "vmf:pattern:python", value = "...") with a Python re regular expression; the generator rejects the model without it. Validation uses an explicit worklist stack so deep containment chains do not hit Python's recursion limit.

Traversal (G)

Rule Python
traverse (G1, G2) ModelSnapshot.traverse(x, strategy) with "containment_tree", "unique_node" (default), or "unique_property"; returns an Iterator[object] and yields read-only views when traversing a read-only view
enter/exit visitor (G3) ModelSnapshot.visit(x, on_enter, on_exit, strategy) (default "unique_node")
writable cursor (G4–G6) ModelSnapshot.open_containment_cursor(x) / ModelSnapshot.open_graph_cursor(x, strategy) (default "unique_node"): move_next(), current, peek(), can_replace, replace_current(replacement), can_insert_after, insert_after_current(inserted), close(); rejects read-only/immutable roots at open time and invalid/stale edits at edit time

Target-specific features and limitations

Python implements all 12 applicable modules of the portable contract (including native structural __eq__/__hash__ under equality-modes, JSON snapshots, and traversal/cursors), with zero external runtime dependencies and full PEP 484 / PEP 561 type annotations (py.typed).

The Python generator rejects models that use generic immutable types, collection defaults that are redeclared or declared by interface-only or generic types, delegated methods on generic types, overloads with the same number of parameters, delegated Object methods other than toString() (equals, hashCode), and immutable types implementing a getter-only trait whose supertypes are not getter-only traits. External types, non-literal defaults, and non-portable regex patterns require Python bindings (vmf:python:external-type, vmf:python:bind-default, vmf:pattern:python). Optional target-specific features outside the contract — XML, YAML, Draft-07 JSON Schema, feature bundles, builders, shallow copy, list sort/removeIf, and V1 preview change journals — are not included in the Python runtime.

:vmf:verifyPythonStockModels generates all 73 stock model packages of test-suite and vmf-jackson, compiles them, and imports every generated module; :vmf:verifyPythonWorkshop verifies four-way JSON interchange across Java, C#, TypeScript, and Python.