sonolus.script.record¶
For usage details, see the corresponding concepts page.
Record
¶
Bases: GenericValue
Base class for user-defined data structures.
Note
A field whose type is itself a reference type, such as another Record or an Array, stores a reference to
the value passed to the constructor rather than a copy, so mutating one mutates the other. Assigning to such
a field afterward copies the assigned value's data into the field's existing storage in place rather than
rebinding the field, so the update is visible through any other reference to that storage. Fields of a value
type such as Num are always independent, both at construction and on assignment.
class Box[T](Record):
value: T
inner = Box(1)
outer = Box(inner) # outer.value aliases inner; no copy is made
inner.value = 2
assert outer.value.value == 2 # mutating inner is visible through outer
outer.value = Box(3) # copies the new value into the shared storage in place
assert inner.value == 3 # inner is updated too, since outer.value still aliases it
A field annotated with typing.Final is set when the record is created and cannot be assigned
afterward. Finality applies to the binding rather than to the data behind it, so the contents of a
Final field of a reference type can still be changed through it.
class Marker(Record):
time: Final[float]
hit: bool
marker = Marker(1.0, False)
marker.hit = True # allowed
marker.time = 2.0 # rejected
Usage
A regular record:
class MyRecord(Record):
field1: int
field2: bool
A generic record:
class MyGenericRecord[T, U](Record):
field1: T
field2: U
Creating an instance:
record = MyRecord(field1=42, field2=True)
record_2 = MyGenericRecord[int, int](field1=42, field2=100)
record_3 = MyGenericRecord(field1=42, field2=100) # Type arguments can be inferred
record_4 = +MyRecord # Create a zero-initialized record
record_5 = +MyGenericRecord[int, int]
Copying a record:
record_copy = +record
type_var_value(var: TypeVar) -> Any
classmethod
¶
Return the value of a type variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
TypeVar
|
The type variable to get the value of. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The value of the type variable. |