Skip to content

Instantly share code, notes, and snippets.

@shayelkin
Last active August 29, 2015 13:56
Show Gist options
  • Save shayelkin/9323181 to your computer and use it in GitHub Desktop.
Save shayelkin/9323181 to your computer and use it in GitHub Desktop.
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