用于健全性检查的循环函数参数
我有一个 Python 函数,在其中对输入参数进行一些清理:
def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
这满足了作为 None 而不是空字符串传递的参数。 是否有一种更简单/更简洁的方法来循环函数参数以将这样的表达式应用于所有参数。 我的实际函数有九个参数。
I have a Python function in which I am doing some sanitisation of the input parameters:
def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于装饰师来说,这看起来是一份不错的工作。 怎么样:
您可以像这样在函数中使用它:
然后,如果参数为 false,则参数将被空字符串替换:(
请注意,正如 Ned Batchelder 在他的回答中指出的那样,这仍然会弄乱函数签名。修复您可以使用 Michele Simionato 的装饰器模块 - 我认为您只需要添加
sanitized
定义之前的@decorator
)This looks like a good job for a decorator. How about this:
You would use this on your function like so:
Then the parameters will be replaced by the empty string if they are false:
(Note that this will still mess up the function signature as Ned Batchelder points out in his answer. To fix that you could use Michele Simionato's decorator module-- I think you'd just need to add a
@decorator
before the definition ofsanitized
)您可以进行一些列表操作:
但我不确定这比只写出九行更好,因为一旦您达到九个参数,那将是一个令人发指的长行。
您可以更改函数的声明:
但是您会丢失来自真实参数名称的文档,以及更改默认值的可能性等。而且您仍然有一个非常难看的行来解压它们。
我说写出九行,或者更改函数以减少参数:无论如何,九行已经很多了!
You could do some list manipulation:
but I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line.
You could change the declaration of the function:
but then you lose the documentation that comes from having real parameter names, as well as the possibility of changing the defaults, etc. And you still have a pretty fugly line there to unpack them.
I say write out the nine lines, or change the function to have fewer parameters: nine is kind of a lot anyway!