pak.types.enum

Enumeration Types.

class Enum(elem_type, enum_type)[source]

Bases: Type

Maps a Type to an enum.Enum.

The default value of the Type is the first member of the enum.

Parameters:
  • elem_type (typelike) – The underlying Type.

  • enum_type (subclass of enum.Enum) – The enum to map values to.

Examples

>>> import enum
>>> import pak
>>> class MyEnum(enum.Enum):
...     A = 1
...     B = 2
...
>>> EnumType = pak.Enum(pak.Int8, MyEnum)
>>> EnumType
<class 'pak.types.enum.Enum(Int8, MyEnum)'>
>>> EnumType.default()
<MyEnum.A: 1>
>>> EnumType.pack(MyEnum.B)
b'\x02'
>>> EnumType.unpack(b"\x02")
<MyEnum.B: 2>
>>> EnumType.unpack(b"\x03") is pak.Enum.INVALID
True
elem_type = None
enum_type = None
INVALID = INVALID
class EnumOr(elem_type, enum_type)[source]

Bases: Type

Maps a Type to an enum.Enum if possible.

This Type should be used for when values only potentially have semantic meaning. This could be for instance when a client sends some user-sourced input to the server, which generally should be of a set of expected values, i.e. the enum.Enum in question, but under valid operation could still be some value outside of that expected set. Like if say a client is expected to send "red", "blue", or "green" to the server, but the user is capable of sending some other string like "pink".

The default value of the Type is the first member of the enum.

When assigning to fields of this Type, the assigned value will be attempted to be converted to the relevant enum.Enum.

Parameters:
  • elem_type (typelike) – The underlying Type.

  • enum_type (subclass of enum.Enum) – The enum to map values to.

Examples

>>> import enum
>>> import pak
>>> class MyEnum(enum.Enum):
...     A = 1
...     B = 2
...
>>> EnumOrType = pak.EnumOr(pak.Int8, MyEnum)
>>> EnumOrType
<class 'pak.types.enum.EnumOr(Int8, MyEnum)'>
>>> EnumOrType.default()
<MyEnum.A: 1>
>>> EnumOrType.pack(MyEnum.B)
b'\x02'
>>> EnumOrType.unpack(b"\x02")
<MyEnum.B: 2>
>>> EnumOrType.pack(3)
b'\x03'
>>> EnumOrType.unpack(b"\x03")
3
>>>
>>> class MyPacket(pak.Packet):
...     field: EnumOrType
...
>>> p = MyPacket()
>>> p
MyPacket(field=<MyEnum.A: 1>)
>>>
>>> # Assigning '2' to the field will convert it to 'MyEnum.B':
>>> p.field = 2
>>> p
MyPacket(field=<MyEnum.B: 2>)
>>>
>>> # Assigning '3' to the field will not convert it to anything:
>>> p.field = 3
>>> p
MyPacket(field=3)
elem_type = None
enum_type = None