Skip to content

Instantly share code, notes, and snippets.

@zerko
Created October 26, 2010 09:09
Show Gist options
  • Save zerko/646574 to your computer and use it in GitHub Desktop.
Save zerko/646574 to your computer and use it in GitHub Desktop.
for habr
import unittest
import logging
logging.basicConfig(level = logging.DEBUG)
log = logging.getLogger("messaged.expression")
class MessagedExpression(object):
def __init__(self, val, msg):
self.msg = msg
self.val = val
self.bool = None
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
if self.bool is not None:
return self.bool
if callable(self.val):
log.debug("%s evaluated" % self.val)
self.val = self.val()
return bool(self.val)
def __and__(self, other):
if bool(self) == False:
return self
self.bool = bool(other)
self.msg = other.msg
return self
def __or__(self, other):
if bool(self) == True:
return self
else:
if not bool(other):
if self.msg.__class__ is not list:
self.msg = [self.msg,]
self.msg.append(other.msg)
self.bool = bool(other)
return self
_me = MessagedExpression
def calculate_me():
log.debug("hardcore calculations")
class Test(unittest.TestCase):
def test(self):
result = _me("123","first") & _me(False, "second") & _me(calculate_me,"calculated")
self.assertEqual(result.msg,"second")
result = _me("123","first") & _me(False, "second") | _me(calculate_me,"calculated")
self.assertEqual(result.msg,["second","calculated"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment