From f2e63aec6e436603b5403fce883e3446db6fe79c Mon Sep 17 00:00:00 2001
From: Anael Beutot <anael.beutot@smartjog.com>
Date: Mon, 23 Apr 2012 11:15:01 +0200
Subject: [PATCH] Tags function can have an argument.

---
 ccnode/tags.py | 34 +++++++++++++++++++++++-----------
 1 file changed, 23 insertions(+), 11 deletions(-)

diff --git a/ccnode/tags.py b/ccnode/tags.py
index c6503d8..9be408d 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):
-- 
GitLab