用于动态注册、检查和处理嵌套参数规范的模块。
canonical-args的Python项目详细描述
canonical_args是一个包,旨在为抽象方法调用提供一些确定性。例如,考虑我们需要为不受控制的包调用许多可能的方法之一。这些方法中的每一个都有相同的参数,但是可能的值会根据函数而改变。我们可以为这些方法中的每一个编写canonical_argsarg规范,这样我们就可以清楚地知道动态执行时每个参数需要是什么(类型、值等):
{ "args": [ { "name": "argument1", "type": int, "values": "range(0, 15)" }, { "name": "argument2", "type": "one([int, float, str])", "values": { "int": ">0", "float": ">0", "str": ["A", "B", "C"] } } ], "kwargs": { "loss_function": { "type": str, "values": ["quadratic", "0-1"] } } }
我们可以将这个规范与一个方法相关联,或者注册它(如果我们不控制方法源):
from canonical_args import register_spec # associates the spec to the method register_spec(somemethod, spec) # method instance method returns the registered spec print somemethod.get_spec()
或者通过修饰一个方法,如果我们控制了它(比如说动态导入的方法处理程序子方法)。
from canonical_args import argspec @arg_spec(spec, register=True) def ourmethod(argument1, argument2, loss_function="quadratic"): pass print ourmethod.get_spec()
这对于动态生成带有类型和值检查代码的前端代码可能有很大的用处。规范本身可以存储在文件或数据库中,允许完全动态的方法调用:
from canonical_args import check_args import pymongo conn = pymongo.MongoClient("localhost", 27017) def handle(message_type, *args, **kwargs): spec = conn.somedatabase.arg_specs.find_one( {"message_type": message_type}) subhandler = conn.somedatabase.handlers.find_one( {"message_type": message_type}) # use canonical_args to check the unknown arguments # against the retrieved spec. will raise AssertionError # if fails. check_args(spec, *args, **kwargs) # if no errors raised, fire the retrieved handler method return subhandler(*args, **kwargs) def get_handler_spec(message_type): """ get the arg spec without executing the function. can be used at front end (eg. HTML) for generating an appropriate form for method calls. """ return conn.somedatabase.handlers.find_one( {"message_type": message_type})
上面的代码不会直接将规范注册到subhandler方法,因为这样做并不总是可取的。选择权在你。
未来工作
我的目标是直接在模块中提供前端代码生成,可能是在子包中。至少要处理html <form>生成,可能使用javascript类型匹配。正在开发中!(https://github.com/shonteag/canonical_args_frontend/)
安装
简单如下:
pip install canonical_args
运行测试:
git clone https://github.com/shonteag/canonical_args nosetests