rberga06.utils.types.Mut#
- final class rberga06.utils.types.Mut(value: _T, /)#
Bases:
Generic
[_T
],SupportsPydanticV2
[Mut[_T] | _T
]Flexible, static, mutable strong reference to a value.
- Example:
>>> # Immutable data >>> data = 42 >>> m0 = Mut(data) >>> m1 = m0 >>> m2 = Mut(data) >>> m0 is m1 True >>> m0 is m2 False >>> print(m0, m1, m2) Mut(42) Mut(42) Mut(42) >>> m0._ = 69 >>> print(m0, m1, m2) Mut(69) Mut(69) Mut(42) >>> >>> # Mutable data >>> data = [42] >>> m0 = Mut(data) >>> m1 = m0 >>> m2 = Mut(data) >>> m3 = Mut(data.copy()) >>> m0 is m1 True >>> m0 is m2 False >>> m0 is m3 False >>> print(m0, m1, m2, m3) Mut([42]) Mut([42]) Mut([42]) Mut([42]) >>> m0._[0] = 33 >>> print(m0, m1, m2, m3) Mut([33]) Mut([33]) Mut([33]) Mut([42]) >>> m0._ = [69] >>> print(m0, m1, m2, m3) Mut([69]) Mut([69]) Mut([33]) Mut([42])
Mut
is most useful when you need to pass around an immutable piece of data (like, in the example,int
instances), without bothering to use a fulllist
, where data access might be less readable and more error-prone - compare(l := [42])[0]
with(m := Mut(42)).value
…Mut
can also be used as a Pydantic model field, because it implementsSupportsPydanticV2
.Caution
Nesting
Mut
instances (for example,Mut(Mut(42))
) is possible, but strongly discouraged. There are two reasons for this:There is no use case for this. If an object is already a Mut, why wrapping it _again_ into a Mut? To get the exact same behaviour the object already has?
The Pydantic compatibility API (see
SupportsPydanticV2
) is designed to allow the following:>>> Mut[int].validate(42) Mut(42) >>> Mut[int].validate(Mut(42)) Mut(42)
It’s not yet possible to access bound type parameters at runtime with consistency (see https://github.com/python/typing/issues/629); this means it’s impossible to distinguish between these two calls:
>>> Mut[int].validate(Mut(42)) Mut(42) >>> Mut[Mut[int]].validate(Mut(42)) Mut(42)
Methods
__init__
(value, /)get
()Get the inner value.
set
(value, /)Set the inner value.
validate
(obj)Instantiate this class from
obj
.Attributes
The inner value.
- get() _T #
Get the inner value.
- value: _T#
The inner value. Also accessible via the
_
property.