Skip to content
Snippets Groups Projects
Commit f2e63aec authored by Anael Beutot's avatar Anael Beutot
Browse files

Tags function can have an argument.

parent 80ef8890
No related branches found
No related tags found
No related merge requests found
import inspect import inspect
import logging import logging
import time import time
import weakref
from functools import partial
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -8,19 +10,32 @@ logger = logging.getLogger(__name__) ...@@ -8,19 +10,32 @@ logger = logging.getLogger(__name__)
class Tag(object): class Tag(object):
"""``class`` that abstract tags and act as a simple container.""" """``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 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 :param None,int ttl: Time to live for caching the tags, possible values
are: are:
* None (means no ttl) * None (means no ttl)
* -1 (means infinite ttl) * -1 (means infinite ttl)
* positive integer in seconds * 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.name = name
self._value = valuable
self.ttl = ttl 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 @property
def value(self): def value(self):
...@@ -28,14 +43,11 @@ class Tag(object): ...@@ -28,14 +43,11 @@ class Tag(object):
call the function. call the function.
""" """
if inspect.isfunction(self._value): try:
try: return self._value()
return self._value() except Exception:
except Exception: logger.exception(u'Calculating tag %s failed:', self.name)
logger.exception(u'Calculating tag %s failed:' % self.name) return None
return None
return self._value
class DynamicTags(object): class DynamicTags(object):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment