简体   繁体   English

使用Python在稀疏数组中存储函数

[英]Storing functions in a sparse array with Python

I have a relatively large enum wherein each member represents a message type. 我有一个相对较大的枚举,其中每个成员代表一种消息类型。 A client will receive a message containing the integer value associated with the msg type in the enum. 客户端将收到一条消息,其中包含与枚举中的msg类型关联的整数值。 For each msg type there will be an individual function callback to handle the msg. 对于每个msg类型,将有一个单独的函数回调来处理msg。

I'd like to make the lookup and dispatching of the callback as quick as possible by using a sparse array (or vector) in which the enum value maps to the index of the callback. 我想通过使用稀疏数组(或向量)尽可能快地查找和调度回调,其中枚举值映射到回调的索引。 Is this possible in Python given arrays can't hold function types? 这是否可能在Python中给定数组不能保存函数类型?

#pseudo code for 'enum'
class MsgType(object):
    LOGIN, LOGOUT, HEARTBEAT, ... = range(n)

#handler class
class Handler(object):
    def handleMsg(self, msg):
        #dispatch msg to specific handler

    def __onLogin(self, msg):
        #handle login

    def __onLogout(self, msg):
        #handle logout

Update: I wasn't clear in my terminology. 更新:我的术语不清楚。 I now understand Python dictionary lookups to be of complexity O(1) which makes them the perfect candidate. 我现在理解Python字典查找具有复杂性O(1),这使它们成为完美的候选者。 Thanks. 谢谢。

class MsgID(int):
    pass

LOGIN = MsgID(0)
LOGOUT = MsgID(1)
HEARTBEAT = MsgID(2)
... # add all other message identifier numbers

class MsgType(object):
    def __init__(self, id, data):
        self.id = id
        self.data = data


def login_handler(msg):
    ...  # do something here

def logout_handler(msg):
    ...  # do something here

def heartbeat_handler(msg):
    ...  # do something here


msg_func = {
    LOGIN  : login_handler,
    LOGOUT : logout_handler,
    HEARTBEAT : heartbeat_handler,
    ...
}


class Handler(object):
    def handleMsg(self, msg):
        try:
            msg_func[msg.id](msg)  # lookup function reference in dict, call function
        except KeyError:
            log_error_mesg('message without a handler function: %d' % msg.id)

It's not strictly needed, but I added a subclass of int for message ID. 这不是严格需要的,但我为消息ID添加了一个int的子类。 That way you can check to see if the ID value is really an ID value rather than just some random integer. 这样你就可以检查ID值是否真的是一个ID值,而不仅仅是一些随机整数。

I assume that each message will have an ID value in it, identifying what sort of message it is, plus some data. 我假设每条消息都有一个ID值,标识它是什么类型的消息,加上一些数据。 The msg_func dictionary uses MsgID values as keys, which map to function references. msg_func字典使用MsgID值作为键,映射到函数引用。

You could put all the functions inside a class, but I didn't do that here; 你可以将所有的功能放在一个类中,但我没有在这里做到; they are just functions. 它们只是功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM