首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python: cerberus check_with函数

Python: cerberus check_with函数
EN

Stack Overflow用户
提问于 2020-05-08 15:57:16
回答 2查看 1.2K关注 0票数 1

我想验证一个dict,其中的值遵循以下规则:

List(float)

  • if
  • 值必须是单个floatfloat--它是单个float,如果是List(float),则值必须为1
  • ,每个浮点数必须为正

下面是我的代码和一些测试断言,它们正在正常工作:

代码语言:javascript
复制
import cerberus

v = cerberus.Validator()

schema1 = {
    "key1": {
        "type": ["float", "list"],
        "min": 1,
        "max": 1,
        "schema": {"type": "float", "min": 0},
    }
}
document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.5, 0.3]}
document5 = {"key1": ["0.5", 0.3]}

assert v.validate(document1, schema1)
assert not v.validate(document2, schema1)
assert not v.validate(document3, schema1)
assert v.validate(document4, schema1)
assert not v.validate(document5, schema1)

现在,我必须执行另一个条件:

如果

  • List(float),则floatsum必须等于1

因此,我编写了一个check_with函数,如docs (https://docs.python-cerberus.org/en/stable/validation-rules.html)中所述。

代码语言:javascript
复制
from cerberus import Validator

class MyValidator(Validator):
    def _check_with_sum_eq_one(self, field, value):
        """Checks if sum equals 1"""

        if sum(value) != 1:
            self._error(field, f"Sum of '{field}' must exactly equal 1")

调整后的模式和测试文档如下所示:

代码语言:javascript
复制
v = MyValidator()

schema2 = {
    "key1": {
        "type": ["float", "list"],
        "min": 1,
        "max": 1,
        "schema": {"type": "float", "min": 0, "max": 1, "check_with": "sum_eq_one"},
    }
}

document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.5, 0.3]}  # error
document5 = {"key1": ["0.5", 0.3]}  # error
document6 = {"key1": [0.5, 0.5]}  # error

现在,只要值是List(float)list的第一个元素就会注入到我的函数中,从而导致TypeError: 'float' object is not iterable

在验证document4时,field将是int=0value=0.5。所以错误信息是有意义的。

我想知道,为什么不把整个名单传递给我的职能?我在这里错过了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-13 11:55:18

如果您试图捕获错误并只继续您的函数(如果发生了错误),该怎么办?例如,以这种方式:

代码语言:javascript
复制
class MyValidator(Validator):

def _check_with_sum_eq_one(self, field, value):
    """ Checks whether value is a list and its sum equals 1.0. """
    if isinstance(value, list) and sum(value) != 1.0:
        self._error(str(value), f"Sum of '{field}' must exactly equal 1")


schema2 = {
    "key1": {
        "type": ["list", "float"],
        "min": 1,
        "max": 1,
        "schema": {"type": "float", "min": 0, "max": 1},
        "check_with": "sum_eq_one",
    }
}

v = MyValidator(schema2)

document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.3, 0.5]}  # error
document5 = {"key1": ["0.5", 0.3]}  # error
#document6 = {"key1": [0.5, 0.5]}  # error
assert v.validate(document1)
assert not v.validate(document2)
assert not v.validate(document3)
assert v.validate(document4)
assert not v.validate(document5)
票数 1
EN

Stack Overflow用户

发布于 2020-05-11 14:33:48

下面的答案是正确的。然而,在我看来,这太复杂了。

首先,调整schema2如下:

代码语言:javascript
复制
schema2 = {
    "key1": {
        "type": ["float", "list"],
        "min": 0,
        "max": 1,
        "check_with": "sum_eq_one"
    }
}

接下来,按照以下方式调整_check_with_sum_eq_one

代码语言:javascript
复制
class MyValidator(Validator):
    def _check_with_sum_eq_one(self, field, value):
        """Checks if sum equals 1"""

        if (isinstance(value, float) or isinstance(value, int)) and value != 1:
            self._error(field, f"Sum of '{field}' must exactly equal 1")
        if isinstance(value, list):
            if all([isinstance(x, float) for x in value]):
                if sum(value) != 1:
                    self._error(field, f"Sum of '{field}' must exactly equal 1")
            else:
                self._error(field, f"All list members must be of type ['float']")

最后,断言一切都如预期的那样工作。

代码语言:javascript
复制
v = MyValidator()

document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.5, 0.3]}
document5 = {"key1": ["0.5", 0.3]}
document6 = {"key1": [0.5, 0.5]}

assert v.validate(document1, schema2)
assert not v.validate(document2, schema2)
assert not v.validate(document3, schema2)
assert not v.validate(document4, schema2)
assert not v.validate(document5, schema2)
assert v.validate(document6, schema2)

这里我不喜欢的是,如果所有的列表成员都是float (if all([isinstance(x, float) for x in value]))类型,我需要检查“手动”。在我看来,这个测试属于schema2。但是,我没有在某种程度上成功地调整schema2,即float类型的测试先于check_with验证。

任何进一步简化这项任务的提示将不胜感激。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61683084

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档