pak.types.enum¶
Enumeration Types.
- class Enum(elem_type, enum_type)[source]¶
Bases:
TypeMaps a
Typeto anenum.Enum.The default value of the
Typeis 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:
TypeMaps a
Typeto anenum.Enumif possible.This
Typeshould 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. theenum.Enumin 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
Typeis the first member of the enum.When assigning to fields of this
Type, the assigned value will be attempted to be converted to the relevantenum.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¶