Not all nor any. Just the one.
Project description
Not all nor any: just the one.
one is a simple function to check if there is a unique value that evaluates to True in an iterable, and return it. Optionally, it receives a callable as the test function.
Examples:
>>> 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
Install
pip install one
Usage
from one import one
Patterns and use cases
one could replace the following patterns:
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)
Another pattern, is in a complex guard
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 not one((a, b, c)):
do_something()
A very frequent case is when you have values that must exclude each others.
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')
Send me your examples!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
one-0.2.tar.gz
(5.0 kB
view details)
Built Distribution
one-0.2-py2.py3-none-any.whl
(4.2 kB
view details)
File details
Details for the file one-0.2.tar.gz
.
File metadata
- Download URL: one-0.2.tar.gz
- Upload date:
- Size: 5.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9f489efa3ac24451ebb6cd10cb9219c5f3c6902570cf12b9b917c8c0eaf68e6a |
|
MD5 | 99613ca414efad72cffab776be5e2d79 |
|
BLAKE2b-256 | a773ecb6987eb1d30f97fe00fbd03ae0271cee931e009c2353e223cef07ede37 |
File details
Details for the file one-0.2-py2.py3-none-any.whl
.
File metadata
- Download URL: one-0.2-py2.py3-none-any.whl
- Upload date:
- Size: 4.2 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | bb166547c9e7edf1d439ca1691d570cc6e7eedca063ae2a8c15fb3404c809842 |
|
MD5 | 1e41064229710f855ed81d0224592f03 |
|
BLAKE2b-256 | d9ddfcdb58fd13f2f8df3735f9170fa4036a325f8c81dfcdaf5db1005c217ab9 |