Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Last active April 7, 2021 23:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mgaitan/9258653 to your computer and use it in GitHub Desktop.
Save mgaitan/9258653 to your computer and use it in GitHub Desktop.
Not `all` nor `any`. Just `one`.
def one(iterable):
"""Return the object in the given iterable that evaluates to True.
If the given iterable has more than one object that evaluates to True,
or if there is no object that fulfills such condition, return False.
>>> one((True, False, False))
True
>>> one((True, False, True))
False
>>> one((0, 0, 'a'))
'a'
>>> one((0, False, None))
False
>>> one((True, True))
False
>>> bool(one(('', 1)))
True
License: BSD
"""
iterable = iter(iterable)
for item in iterable:
if item:
break
else:
return False
if any(iterable):
return False
return item
if __name__ == "__main__":
import doctest
doctest.testmod()
@mgaitan
Copy link
Author

mgaitan commented Feb 28, 2014

Use case example

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')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment