diff --git a/ccnode/tags.py b/ccnode/tags.py index c6503d8d0b475dc2fd0c76747ef9d8a25449e593..9be408d90b94c3a8a6bccbf9a4b8f260380cce12 100644 --- a/ccnode/tags.py +++ b/ccnode/tags.py @@ -1,6 +1,8 @@ import inspect import logging import time +import weakref +from functools import partial logger = logging.getLogger(__name__) @@ -8,19 +10,32 @@ logger = logging.getLogger(__name__) class Tag(object): """``class`` that abstract tags and act as a simple container.""" - def __init__(self, name, valuable, ttl=-1): + def __init__(self, name, valuable, ttl=-1, parent=None): """ :param string name: tag name - :param valuable: something that gives tag value, string or function + :param valuable: something that gives tag value, string or callable :param None,int ttl: Time to live for caching the tags, possible values are: * None (means no ttl) * -1 (means infinite ttl) * positive integer in seconds + :param object obj: parent object the tag is attached to, it may be + needed for the tag callable to process the tag """ self.name = name - self._value = valuable self.ttl = ttl + self.parent = parent if parent is None else weakref.proxy(parent) + + if inspect.isfunction(valuable): + args_count = len(inspect.getargspec(valuable).args) + if args_count > 1: + raise Exception('Invalid number of argument for tag function') + elif args_count == 1: + self._value = partial(valuable, self.parent) + else: + self._value = valuable + else: + self._value = lambda: valuable @property def value(self): @@ -28,14 +43,11 @@ class Tag(object): call the function. """ - if inspect.isfunction(self._value): - try: - return self._value() - except Exception: - logger.exception(u'Calculating tag %s failed:' % self.name) - return None - - return self._value + try: + return self._value() + except Exception: + logger.exception(u'Calculating tag %s failed:', self.name) + return None class DynamicTags(object):