summaryrefslogtreecommitdiff
path: root/lib/taurus/core/util/wrap.py
diff options
context:
space:
mode:
Diffstat (limited to 'lib/taurus/core/util/wrap.py')
-rw-r--r--lib/taurus/core/util/wrap.py64
1 files changed, 64 insertions, 0 deletions
diff --git a/lib/taurus/core/util/wrap.py b/lib/taurus/core/util/wrap.py
new file mode 100644
index 00000000..bf82c22e
--- /dev/null
+++ b/lib/taurus/core/util/wrap.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+
+#############################################################################
+##
+## This file is part of Taurus
+##
+## http://taurus-scada.org
+##
+## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
+##
+## Taurus is free software: you can redistribute it and/or modify
+## it under the terms of the GNU Lesser General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## (at your option) any later version.
+##
+## Taurus is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU Lesser General Public License for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with Taurus. If not, see <http://www.gnu.org/licenses/>.
+##
+#############################################################################
+
+""""""
+
+__all__ = ["wraps", "wrapped", "is_wrapping", "is_wrapped"]
+
+import weakref
+from functools import wraps as _wraps
+
+__WRAPPED = "__wrapped__"
+__WRAPPER = "__wrapper__"
+
+def wraps(wrapped, *args, **kwargs):
+ """A wrap decorator which stores in the returned function a reference to
+ the wrapped function (in member '__wrapped__')"""
+ wrapper = _wraps(wrapped, *args, **kwargs)
+ setattr(wrapper, __WRAPPED, weakref.ref(wrapped))
+ setattr(wrapped, __WRAPPER, weakref.ref(wrapper))
+ return wrapper
+
+def is_wrapping(wrapper):
+ """Determines if the given callable is a wrapper for another callable"""
+ return hasattr(wrapper, __WRAPPED)
+
+def is_wrapped(wrapped):
+ """Determines if the given callable is being wrapped by another callable"""
+ return hasattr(wrapped, __WRAPPER)
+
+def wrapped(wrapper, recursive=True):
+ """Returns the wrapped function around the given wrapper. If the given
+ callable is not "wrapping" any function, the wrapper itself is returned"""
+ if is_wrapping(wrapper):
+ _wrapped = wrapper.__wrapped__()
+ else:
+ return wrapper
+
+ if recursive:
+ return wrapped(_wrapped)
+ return _wrapped
+
+ \ No newline at end of file