python中的模式匹配
matchstick的Python项目详细描述
matchstick提供了一个允许python函数重载的decorator。
>>>frommatchstickimportwhen>>>@when('x >= 0')...deff(x):...returnx...>>>@when('x < 0')...deff(x):...return-x...>>>f(3)3>>>f(-2)2>>>f('a')'a'
基本用途
条件
match decorator将条件作为字符串。调用修饰函数时,将按定义顺序检查重载函数(按模块和限定名分组)。使用传递给函数的参数(包括默认参数值,如果适用)计算每个条件。如果条件计算truthy,则调用相应的函数。如果条件计算错误或引发异常,则传递相应的函数。
>>>@when('x[2] == 5')...deff(x):...returnsum(x)...>>>@when('len(x) > 3')...deff(x):...returnx[3:]...>>>@when('True')...deff(x):...returnx...>>>f([3,4,5,6])18>>>f([0,1,2,3])[3]>>>f('abcd')'d'>>>f({}){}
Nomatchexception
如果函数的条件都不求值truthy,则会引发matchstick.nomatchexception。