socktools.msgtype_mixin - reference message types by name

This module implements a mixin that allows you to reference message types as strings. Higher-level protocols can make use of it to offer a more convenient API.

Normally you’d use this to represent message types as integers, but you can also remap message types to other strings here too.

Additionally, this module has another mixin that adds send_MSGTYPE methods to the socket object for each message type.

class socktools.msgtype_mixin.MsgtypeSendMixin[source]

Bases: object

A mixin that adds send_MSGTYPE methods to the socket

This MUST be used with MsgtypeStrMixin first otherwise it will not work:

class MyClass(MsgtypeSendMixin,MsgtypeStrMixin,UDPSock):
      pass

You will of course also need to setup your message types by passing an appropriate dict to the constructor or by overriding get_default_msg_types().

If everything works the object will magically acquire a bunch of send_MSGTYPE methods: 1 per msg_types entry. Note that for performance reasons this is NOT dynamic.

The send_MSGTYPE methods will pass all of their arguments to send_msg()

child_setup()[source]

Setup this mixin

This is where the black magic happens.

class socktools.msgtype_mixin.MsgtypeStrMixin(msg_types={}, **kwargs)[source]

Bases: object

A mixin for referencing message types as strings

This class should be used together with UDPSock, TCPSock or a child of one of those classes:

class MyClass(MsgtypeStrMixin,UDPSock):
   pass

If you do not add an actual socket, this class does nothing, it’s a mixin.

Keyword Arguments:
 msg_types (dict) – maps message types as strings to message type integers (or any other arbitrary object)
msg_types

dict

maps message types as strings to message type integers (or any other arbitrary object)

add_handler(msg_type, handler, exclusive=False)[source]

See base_sock.py for full details

The mixin adds a msg_types lookup and uses the value from msg_types if found. Otherwise this method is identical to the default add_handler().

child_setup()[source]

Setup this mixin

This method configures the handlers by remapping them to appropriate values from the msg_types variable, saving an extra lookup at runtime.

Should a handler be specified directly as an integer or a handler be specified for a message type that does not exist, it will be left as-is.

get_default_msg_types()[source]

Get a default msg_types dict

When inheriting from this class you should override this method and setup appropriate message types. Like get_default_handlers() children should always call this method.

The default implementation returns an empty dict

Returns:a dict mapping message type strings to any other data type (integer is usual)
Return type:dict