pak.types.deferring¶
Types which defer their behavior to other Types.
- class DeferringType[source]¶
Bases:
TypeA
Typewhich defers its behavior to otherTypes.A
DeferringTypewill defer all of its marshaling behavior to a certainTypedepending on what it decides to return from its_defer_to()method.This deferring of behavior is useful, for instance, in protocols with multiple versions, where you may want to have a
Packetfield act like a differentTypebetween different protocol versions.DeferringTypeshould be preferred to customTypes of a similar nature becauseDeferringTypewill forward on all relevant behavior, resulting in a more correct and ergonomic experience.Examples
>>> import pak >>> class VersionedPacket(pak.Packet): ... class Context(pak.Packet.Context): ... def __init__(self, *, version): ... self.version = version ... ... super().__init__() ... ... def __hash__(self): ... return hash(self.version) ... ... def __eq__(self, other): ... if not isinstance(other, VersionedPacket.Context): ... return NotImplemented ... ... return self.version == other.version ... >>> class VersionedInteger(pak.DeferringType): ... @classmethod ... def _defer_to(cls, *, ctx): ... # 'Int8' in version 0, 'Int16' in every other version. ... if ctx.version == 0: ... return pak.Int8 ... ... return pak.Int16 ... >>> class MyPacket(VersionedPacket): ... number: VersionedInteger ... >>> p = MyPacket(number=2) >>> >>> # The 'number' field is an 'Int8' in version 0. >>> p.pack(ctx=VersionedPacket.Context(version=0)) b'\x02' >>> >>> # The 'number' field is an 'Int16' in version 1. >>> p.pack(ctx=VersionedPacket.Context(version=1)) b'\x02\x00'
- exception UnableToDeferError[source]¶
Bases:
ValueError,UnsuppressedErrorAn error indicating that there was no appropriate
Typeto defer to.
- classmethod _defer_to(*, ctx)[source]¶
Gets the
Typewhich theDeferringTypeshould defer to.This method should be overridden by subclasses.
- Parameters:
ctx (
Type.Context) – The context for theType.- Returns:
The appropriate
Typeto defer to based on thectxparameter.- Return type:
subclass of
Type- Raises:
UnableToDeferError – If the
DeferringTypeis unable to defer to an appropriateType.