pak.types.type¶
Base code for Types.
- class Type(typelike)¶
Bases:
objectA definition of how to marshal raw data to and from values.
Typically used for the types of
Packetfields.When
Typesare called, their_call()classmethodgets called, returning a newType.Arraytypes can be constructed using indexing syntax, like so:>>> import pak >>> array = pak.Int8[3] >>> array <class 'pak.types.array.Int8[3]'> >>> array.pack([1, 2, 3]) b'\x01\x02\x03' >>> array.unpack(b"\x01\x02\x03") [1, 2, 3]
The object within the brackets gets passed as the
sizeparameter toArray.- Parameters:
typelike – The typelike object to convert to a
Type.- Raises:
TypeError – If
typelikecan’t be converted to aType.
- class Context(packet=None, *, ctx=None)¶
Bases:
objectThe context for a
Type.Type.Contexts are used to pass arbitrary data toTypes. All of that arbitrary data comes from the attributes of thePacket.Contextif supplied, and you may access those attributes on the createdType.Contextas if it were thePacket.Contextitself.However, a
Type.Contextalso contains apacketattribute which denotes thePacketinstance for which aTypeutility is being used for, if any is applicable.Note
Unlike
Packet.Context, this should not be customized.- Parameters:
packet (
Packet) – The packet instance that’s being marshaled.ctx (
Packet.Context) –The context for the packet that’s being marshaled.
Getting attributes that are not directly in the
Type.Contextwill be gotten from the packet context.
- packet_ctx¶
The context for the packet that’s being marshaled.
Getting attributes that are not directly in the
Type.Contextwill be gotten from this.- Type:
Packet.ContextorNone
- STATIC_SIZE = STATIC_SIZE¶
- exception UnpackMethodNotImplementedError(type_cls, *, is_async)¶
Bases:
NotImplementedError,UnsuppressedErrorAn error indicating a
Typehas not implemented a certain method for unpacking.
- exception UnsuppressedError¶
Bases:
ExceptionAn error that is left unsuppressed by certain
Typeoperations.Certain
Typeoperations, such as unpackingArray.UnboundedandOptional.Unchecked, involve suppressing a generalException, preventing its propagation through the program.Such operations will neglect to suppress a
Type.UnsuppressedErrorhowever, enabling it to signal that something unambiguously wrong has occurred.
- classmethod __class_getitem__(index)¶
-
- Parameters:
index (
intor subclass ofTypeorstrorfunctionorNone) – Thesizeargument passed toArray.
Examples
>>> import pak >>> pak.Int8[3] <class 'pak.types.array.Int8[3]'>
- classmethod _array_default(array_size, *, ctx)¶
Gets the default value for an
Arraywith theTypeas its element.- Parameters:
array_size (
int) – The number of elements to create a default for.ctx (
Type.Context) – The context for theType.
- Returns:
The default value for an
Arraywith theTypeas its element.- Return type:
any
- classmethod _array_ensure_size(value, array_size, *, ctx)¶
Ensures the value of an
Arraywith theTypeas its element is the correct size.- Parameters:
value – The value to ensure is the correct size.
array_size (
int) – The number of elements that the value should hold.ctx (
Type.Context) – The context for theType.
- Returns:
The value of the
Arraywhich hasarray_sizeelements.- Return type:
any
- classmethod _array_num_elements(value, *, ctx)¶
Gets the number of elements for an
Arraywith theTypeas its element.This method is only called when the
Arrayis prefixed by aTypeor has a size ofNone, meaning it should read until the end of aPacket, since in all other cases the number of elements is predetermined.- Parameters:
value – The value to get the number of elements of.
ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding number of elements for
value.- Return type:
int
- classmethod _array_pack(value, array_size, *, ctx)¶
Packs the value of an
Arraywith theTypeas its element.- Parameters:
value – The value of the
Array.array_size (
int) – The number of elements in theArray.ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding raw data of the
Array.This only includes the body of the
Array, not length prefixes or anything of that sort.- Return type:
bytes
- classmethod _array_static_size(array_size, *, ctx)¶
Gets the static size of an
Arraywith theTypeas its element.- Parameters:
array_size (
int) – The number of elements to get the size of.ctx (
Type.Context) – The context for theType.
- Returns:
The size of the raw data of an
Arrayof sizearray_size.If
None, then no static size exists.This only includes the body of the
Array, not length prefixes or anything of that sort.- Return type:
intorNone
- classmethod _array_transform_value(value)¶
Transforms the value of an
Arrayfield with theTypeas its element.Called when the descriptor form of an
Arrayhas its value set.- Parameters:
value – The original value.
- Returns:
The transformed value.
This transformed value will be the one that gets set.
- Return type:
any
- classmethod _array_unpack(buf, array_size, *, ctx)¶
Unpacks an
Arraywith theTypeas its element.See also
- Parameters:
buf (file object) – The buffer containing the raw data.
array_size (
intorNone) –The number of elements to unpack.
If
None, then as many elements as possible should be unpacked frombuf.ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding value for an
Arraywith theTypeas its element.- Return type:
any
- async classmethod _array_unpack_async(reader, array_size, *, ctx)¶
Asynchronously unpacks an
Arraywith theTypeas its element.See also
- Parameters:
reader (
asyncio.StreamReader) – The stream of data to unpack from.array_size (
intorNone) –The number of elements to unpack.
If
None, then as many elements as possible should be unpacked fromreader.ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding value for an
Arraywith theTypeas its element.- Return type:
any
- classmethod _call()¶
Called when the
Typeis called.The arguments passed to the
Typewill be forwarded to this method, which may be overridden to generate a newTypebased on the calledType.
- classmethod _pack(value, *, ctx)¶
Packs a value into its corresponding raw data.
To be overridden by subclasses.
Warning
Do not use this method directly, always use
pack()instead.- Parameters:
value – The value to pack.
ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding raw data.
- Return type:
bytes
- classmethod _unpack(buf, *, ctx)¶
Unpacks raw data into its corresponding value.
To be overridden by subclasses.
Warning
Do not use this method directly, always use
unpack()instead.- Parameters:
buf (file object) – The buffer containing the raw data.
ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding value of the raw data.
- Return type:
any
- async classmethod _unpack_async(reader, *, ctx)¶
Asynchronously unpacks raw data into its corresponding value.
To be overridden by subclasses.
Warning
Do not use this method directly, always use
unpack_async()instead.- Parameters:
reader (
asyncio.StreamReader) – The stream of data to unpack from.ctx (
Type.Context) – The context for theType.
- Returns:
The corresponding value of the raw data.
- Return type:
any
- classmethod alignment(*, ctx=None)¶
Gets the alignment of the
Type.The alignment of a
Typemust be a power of two.The alignment of a
Typeis typically ignored, unless using something that explicitly utilizes alignment, such asAlignedPacket.Furthermore, alignment only makes sense for
Types with static sizes.If the
_alignmentattribute is any value other thanNone, then that value will be returned.Else, if the
_alignmentattribute is aclassmethod, then it should look like this:@classmethod def _alignment(cls, *, ctx): return my_alignment
The return value of the
classmethodwill be returned from this method.Otherwise, if the
_alignmentattribute is aDynamicValue, which it is automatically transformed into on class construction if applicable, then the dynamic value of that is returned.If any of these give a value of
None, then theTypehas no alignment and aTypeErrorwill be raised.- Parameters:
ctx (
Type.ContextorNone) –The context for the
Type.If
None, then an emptyType.Contextis used.- Returns:
The alignment of the
Type.- Return type:
int- Raises:
TypeError – If the
Typehas no alignment.
- static alignment_padding_lengths(*types, total_alignment, ctx=None)¶
Gets the length of padding after each
Typefor alignment purposes.Should rarely be used by users. In most cases
AlignedPacketshould be used.- Parameters:
*types (subclass of
Type) – TheTypes for which to find the padding for.total_alignment (
int) – The total alignment that*typesshould be aligned to, used for the padding at the end.ctx (
Type.ContextorNone) –The context for
*types.If
None, then an emptyType.Contextis used.
- Returns:
The lengths of padding after each
Typein*types.- Return type:
list
- classmethod default(*, ctx=None)¶
Gets the default value of the
Type.If the
_defaultattribute is aclassmethod, then it should look like this:@classmethod def _default(cls, *, ctx): return my_default_value
The return value of the
classmethodwill be returned from this method.Else, if the
_defaultattribute is aDynamicValue, which it is automatically transformed into on class construction if applicable, then the dynamic value of that is returned.Otherwise, if the
_defaultattribute is any value other thanNone, a deepcopy of that value will be returned.- Parameters:
ctx (
Type.ContextorNone) –The context for the
Type.If
None, then an emptyType.Contextis used.- Returns:
The default value.
- Return type:
any
- Raises:
TypeError – If the
Typehas no default value.
- classmethod is_typelike(obj)¶
Gets whether an object is typelike.
- Parameters:
obj – The object to check.
- Returns:
Whether
objis typelike.- Return type:
bool
- classmethod make_type(name, bases=None, /, **namespace)¶
Utility for generating new types.
The generated type’s
__module__attribute is set to be the same as the origin type’s. This is done to get around an issue where generated types would have their__module__attribute be otherwise unintuitve.This method is cached so a new type is only made if it hasn’t been made before.
- Parameters:
name (
str) – The generated type’s name.bases (
tupleorNone) –The generated type’s base classes.
If
None, the origin type is the sole base class.**namespace – The attributes and corresponding values of the generated type.
- Returns:
The generated type.
- Return type:
subclass of
Type
- classmethod pack(value, *, ctx=None)¶
Packs a value into its corresponding raw data.
Warning
Do not override this method. Instead override
_pack().- Parameters:
value – The value to pack.
ctx (
Type.ContextorNone) –The context for the
Type.If
None, then an emptyType.Contextis used.
- Returns:
The corresponding raw data.
- Return type:
bytes
- static prepare_types(func)¶
A decorator that converts arguments annotated with
Typeto aType.Note
The decorated
functionwill not retain its annotations of parameters that are annotated withType, as the purpose of annotating a parameter withTypein this context is not for type hinting, and is only really relevant to the implementation of thefunction, and otherwise could be confusing.Examples
>>> import pak >>> @pak.Type.prepare_types ... def example(arg: pak.Type): ... print(arg.__qualname__) ... >>> example(pak.Int8) Int8 >>> example(None) EmptyType
- classmethod register_typelike(typelike_cls, converter)¶
Registers a class as being convertible to a
Type.- Parameters:
typelike_cls (
type) – The convertible type.converter (callable) – The object called to convert the object to a
Type.
- classmethod size(value=STATIC_SIZE, /, *, ctx=None)¶
Gets the size of the
Typewhen packed.Worst case this will perform as badly as packing the value and getting the length of the raw data performs. However,
Types may often be able to optimize finding their packed sizes.If the
_sizeattribute is any value other thanNone, then that value will be returned.Else, If the
_sizeattribute is aclassmethod, then it should look like this:@classmethod def _size(cls, value, *, ctx): return my_size
The return value of the
classmethodwill be returned from this method.Otherwise, if the
_sizeattribute is aDynamicValue, which it is automatically transformed into on class construction if applicable, then the dynamic value of that is returned.If any of these give a size of
Noneor raiseNoStaticSizeError, then ifvalueis notSTATIC_SIZE, then the value will be packed in order to get the size.- Parameters:
value (any) –
If
STATIC_SIZE, then a size irrespective of any value is returned, if possible.Otherwise,
ctx (
Type.ContextorNone) –The context for the
Type.If
None, then an emptyType.Contextis used.
- Returns:
The size of the
Typewhen packed.- Return type:
int- Raises:
NoStaticSizeError – If the
Typehas no static size but is asked for one.
- classmethod unpack(buf, *, ctx=None)¶
Unpacks raw data into its corresponding value.
Warning
Do not override this method. Instead override
_unpack().See also
- Parameters:
buf (file object or
bytesorbytearray) – The buffer containing the raw data.ctx (
Type.ContextorNone) –The context for the
Type.If
None, then an emptyType.Contextis used.
- Returns:
The corresponding value of the raw data.
- Return type:
any
- async classmethod unpack_async(reader, *, ctx=None)¶
Asynchronously unpacks raw data into its corresponding value.
Warning
Do not override this method. Instead override
_unpack_async().See also
- Parameters:
reader (
asyncio.StreamReaderorbytesorbytearray) –The stream of data to unpack from.
Warning
Nothing else should read from
readeruntil this coroutine finishes executing.If
bytesorbytearray, thenreaderis turned into anio.ByteStreamReader.ctx (
Type.ContextorNone) –The context for the
Type.If
None, then an emptyType.Contextis used.
- Returns:
The corresponding value of the raw data.
- Return type:
any
- exception NoStaticSizeError(type_cls)¶
Bases:
ExceptionAn error indicating a
Typehas no static size.
- exception MaxBytesExceededError(type_cls)¶
Bases:
UnsuppressedErrorAn error indicating a
Typehas exceeded its maximum number of bytes when unpacking.