跳转到主要内容

Python自动绑定字典

项目描述

bdict

一个库,允许您创建一个自动方法绑定字典。

是否曾梦想编写简洁的字典,将键指向方法?不再需要担心了!

主要用于事件处理,绑定字典由任何事件或键与其相应的处理函数在类内部之间的映射组成。在键查找时,字典将绑定适当的函数到类的实例。

示例

class Server:
    """Typical server with a small mapping between event handlers and functions"""
    def __init__(self, name):
        self.name = name

    def on_connect(self, remote_host):
        print(self.name, remote_host)

    def on_connect(self, remote_host):
        print(self.name, remote_host)

    handlers = BDict({NewConnectionEvent: on_connect,
                      DisconnectonEvent: on_disconnect})

>>> s = Server("myserver")
>>> s.handlers[NewConnectionEvent]("1.2.3.4")
myserver 1.2.3.4

如您所见,在访问处理程序字典并在键查找后,字典将处理程序函数绑定到实例。

BDict还可以以干净的方式与类方法一起使用

class MyClass:
    """Typical server with a small mapping between event handlers and functions"""            
    @classmethod
    def class_handle(cls):
        print(cls.__name__)

    handlers = BDict({"class_handle": class_handle})

>>> MyClass.handlers["class_handle"]
<bound method MyClass.class_handle of <class '__main__.MyClass'>>
>>> MyClass.handlers["class_handle"]()
MyClass

>>> inst = MyClass()
>>> inst.handlers["class_handle"]
<bound method MyClass.class_handle of <class '__main__.MyClass'>>
>>> inst.handlers["class_handle"]()
MyClass

通过实例访问BDict时,BDict将在BDict上创建一个内部实例数据容器,允许您修改它的字典,而不会影响其他实例!

>>> inst.handlers[123] = 456
>>> inst.handlers[123]
456
>>> inst2 = MyClass()
>>> inst2.handlers[123]
Traceback (most recent call last):
  ...
KeyError: 123

用法

BDict(dict_)

dict_可以是字典或(key, value)对的迭代器,并将其用于初始化BDict

类BDict必须支持弱引用(绝大多数自定义对象都这样做)。如果您使用__slots__,可以通过向插槽添加__weakref__来实现。

BDict.autobind(key, value)

允许在字典中添加自动绑定条目(常规添加不会自动绑定)。key是访问键,而value是要自动绑定的函数。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

bdict-0.1.0.tar.gz (3.9 kB 查看哈希值)

上传时间

构建分发

bdict-0.1.0-py3-none-any.whl (4.4 kB 查看哈希值)

上传时间 Python 3

由以下机构支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误日志StatusPageStatusPage状态页面