Last active
August 29, 2015 13:56
-
-
Save shayelkin/9323181 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BooleanFunctor: | |
""" | |
A neat trick: this can be used in conditions, where it returns the value of b, | |
or as a decorator, where it returns the decorated function if b, or a lambda returning | |
falseValue otherwise. | |
>>> if BooleanFunctor(cond): | |
... # only if cond is true | |
... pass | |
>>> @BooleanFunctor(cond) | |
... def foo(): | |
... pass | |
>>> # If cond, v would equal foo(), otherwise it'd be falseValue | |
>>> v = foo() | |
""" | |
def __init__(self, b, falseValue=False): | |
self.b = b | |
self.falseValue = falseValue | |
def __nonzero__(self): | |
return self.b | |
def __call__(self, f): | |
return f if self.b else lambda *a, **k: falseValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment