Skip to main content

不是全部,也不是任何。就一个。

项目描述

https://pypip.in/d/one/badge.png https://travis-ci.org/mgaitan/one.svg

不是全部,也不是任何:只有一个

一个是一个简单的函数,用于检查是否有一个唯一值在可迭代对象中计算为 True,然后将其返回。可选地,它接收一个可调用的作为测试函数。

例子:

>>> from one import one
>>> one((True, False, False))
True
>>> one((True, False, True))
False
>>> one((0, 0, 'a'))
'a'
>>> one((0, False, None))
False
>>> one((True, True))
False
>>> one(('', 1))
1
>>> one((10, 20, 30, 42), lambda i: i > 40)
42

安装

pip install one

用法

from one import one

模式和用例

可以替换以下模式:

true_values = [i for i in iterable if cmp(i)]
if len(true_values) == 1:
    return true_values[0]
return False

# using one
return one(iterable, cmp)

另一种模式,处于复杂状态

if ((a and not b and not c) or
     (b and not a and not c) or
      (c and not a and not b)):
    do_something()

# using one
if one((a, b, c)):
    do_something()

一个非常常见的情况是当您的值必须相互排除时。

class ShopStore(models.Model):
    address = models.CharField(max_length=200, null=True, blank=True)
    is_online = models.BooleanField(default=False)

    def clean(self):
        if not one((self.address, self.is_online)):
            raise models.ValidationError(u'A shop must be online or physical, but not both')

把你的例子发给我!

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

one-0.2.1.tar.gz (5.0 kB 查看哈希

已上传 source

内置分布

one-0.2.1-py2.py3-none-any.whl (4.2 kB 查看哈希

已上传 2 7