基于调度的高效调用,可能是在另一种语言中的switch语句。
项目描述
Switcheroo
基于调度的高效调用,可能是在另一种语言中的switch语句。
简短用法
from switcheroo import Switch
switch = Switch({
'foo': lambda x: x+1,
})
>>> switch['foo'](1) 2
>>> switch['bar'](1) Traceback (most recent call last): ... KeyError: 'bar'
from switcheroo import Switch, default
switch = Switch({
'foo': lambda x: x+1,
default: lambda x: x-1,
})
>>> switch['foo'](1) 2
>>> switch['bar'](1) 0
显式用法
from switcheroo import Switch
def handle_foo(x):
return x+1
def handle_others(x):
return x-1
switch = Switch()
switch.register('foo', handler=handle_foo)
switch.default(handle_others)
>>> switch.lookup('foo')(1) 2
>>> switch.lookup('bar')(1) 0
>>> switch.override('foo', lambda x: x+2) >>> switch.lookup('foo')(1) 3
装饰器用法
from switcheroo import Switch
switch = Switch()
@switch.handles('foo')
def handle_foo(x):
return x+1
@switch.default
def handle_others(x):
return x-1
>>> switch['foo'](1) 2
>>> switch['bar'](1) 0
@switch.overrides('foo')
def new_handle_foo(x):
return x+2
>>> switch['foo'](1) 3
类辅助用法
class MoarThingz(object):
switch = Switch()
def __init__(self, state):
self.state = state
@switch.handles('foo')
def handle_foo(self, x):
return self.state - x
@switch.default
def handle_foo(self, x):
return self.state + x
def dispatch(self, case, factor, x):
return factor * self.switch[case](self, x)
>>> things = MoarThingz(3) >>> things.dispatch('foo', factor=1, x=1) 2 >>> things.dispatch('bar', factor=-1, x=2) -5
子类用法
from switcheroo import Switch, handles, default
class MySwitch(Switch):
@handles('foo')
def handles(x):
return x+1
@default
def default(x):
return x-1
>>> MySwitch['foo'](1) 2 >>> MySwitch['bar'](1) 0
更改
2.0.0 (20 Sep 2022)
停止支持Python 2。
1.1.0 (26 Nov 2020)
添加支持覆盖。
添加更显式用法的支持。
1.0.0 (27 Feb 2019)
100%覆盖率检查和自动化发布。
0.2.0 (13 Dec 2018)
在使用子类模式时处理子类。
0.1.0 (24 Nov 2018)
首次发布。
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。
源分布
switcheroo-2.0.0.tar.gz (3.7 kB 查看哈希)
构建分布
switcheroo-2.0.0-py3-none-any.whl (3.4 kB 查看哈希)