跳转到主要内容

简单的类/函数注册。

项目描述

readi 集合

简单的类注册。

我经常发现自己试图实现通用的类表示,然后扩展它们以提供许多不同的功能变体。然后我希望能够以简单、自动的方式访问这些变体,而不必编写“switch-case”类型的类选择策略。

这允许您在实例化时注册类,并通过简单的字典接口访问它们,并有一些很好的辅助方法 :)

安装

pip install readi

用法

# __init__.py
import readi
# this is just a dictionary with some fancy bits
collection = readi.Collection(entrypoints='myentrypoint')
# setup.py
# this can allow other modules to register classes.
setuptools.setup(
    ...
    entry_points={'myentrypoint': ['C = module.for.thisclass:SomeClass']}
)
# myclasses.py
# then just use it in your class
from . import collection

@collection.register
class A:
    pass

class B:
    pass

class B1(B):
    pass

class B2(B):
    pass

collection.register_subclasses(B, include=True)

# they're all available in the collection dictionary.
assert set(collection) == {'a', 'b', 'b1', 'b2', 'c'}

class D(B1): # works for nested subclasses
    pass

collection.refresh_subclasses() # can gather new subclasses
assert set(collection) == {'a', 'b', 'b1', 'b2', 'c', 'd'}
# __main__.py
# now to see how they're used.
from . import collection

def main(**kw):
    processors = collection.gather(**kw)

    for data in data_generator():
        for func in processors: # assuming we defined __call__
            func(data)

main(fs=48000, channels=4, b1=False, b2=dict(nfft=2048))

这样做将生成一个看起来像这样的处理器列表

processors = [
    A(fs=48000, channels=4),
    B(fs=48000, channels=4),
    # B1 is omitted since it was set as False
    B2(fs=48000, channels=4, nfft=2048),
    C(fs=48000, channels=4),
    D(fs=48000, channels=4),
]

如果您有一系列要运行的处理器并且想使用关键字参数启用/禁用它们,则使用此功能。

另一个用例是:您只需要选择一个已注册的类。这很简单完成

# __main__.py
# now to see how they're used.
from . import collection

def main(proc_type='b', **kw):
    processor = collection.getone(proc_type, **kw)

    for data in data_generator():
        processor(data)

main(fs=48000, channels=4, proc_type='b2')

注意

  • 没有任何东西阻止您添加返回非函数值(即列表)的东西。
@collection.register
def reds(saturation=92):
    c = '#FF0000'
    return [c] + calculate_colors(c, saturation)

@collection.register
def blues(saturation=92):
    c = '#0000FF'
    return [c] + calculate_colors(c, saturation)

@collection.register
def greens(saturation=92):
    c = '#00FF00'
    return [c] + calculate_colors(c, saturation)

colors = collection.gather(saturation=120, greens=False)
# colors = [
#     ['#FF0000', ...], # reds
#     ['#0000FF', ...], # blues
# ]

待办事项

项目详情


下载文件

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

源分布

readi-0.1.0.tar.gz (4.0 kB 查看哈希值)

上传时间 源代码

由...