简单的类/函数注册。
项目描述
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 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 48057e3dea37fbf2103167fb3b1928f345035a3e987e2ef80e28a9632a9ff5f9 |
|
MD5 | 61ae8db44c5d98c6b4f9614413483c0f |
|
BLAKE2b-256 | e69820ffb91c454de7af6c59624ec3dfce74ec8c1fd56dfa02d032077d3c3a89 |