changeset 2470:8084066ac95b

tools (utils): new "partial" function which is a hack to workaround issue with functools.partial while using it with dbus module.
author Goffi <goffi@goffi.org>
date Fri, 12 Jan 2018 15:45:37 +0100
parents adcc35625e17
children 544c4d2fec45
files src/tools/utils.py
diffstat 1 files changed, 27 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/tools/utils.py	Fri Jan 05 13:00:34 2018 +0100
+++ b/src/tools/utils.py	Fri Jan 12 15:45:37 2018 +0100
@@ -29,6 +29,9 @@
 import time
 import sys
 import random
+import inspect
+import textwrap
+import functools
 
 
 def clean_ustr(ustr):
@@ -43,6 +46,29 @@
             yield char
     return ''.join(valid_chars(ustr))
 
+def partial(func, *fixed_args, **fixed_kwargs):
+    # FIXME: temporary hack to workaround the fact that inspect.getargspec is not working with functools.partial
+    #        making partial unusable with current D-bus module (in addMethod).
+    #        Should not be needed anywore once moved to Python 3
+
+    ori_args = inspect.getargspec(func).args
+    func = functools.partial(func, *fixed_args, **fixed_kwargs)
+    if ori_args[0] == 'self':
+        del ori_args[0]
+    ori_args = ori_args[len(fixed_args):]
+    for kw in fixed_kwargs:
+        ori_args.remove(kw)
+
+    exec(textwrap.dedent('''\
+    def method({args}):
+        return func({kw_args})
+    ''').format(
+        args = ', '.join(ori_args),
+        kw_args = ', '.join([a+'='+a for a in ori_args]))
+    , locals())
+
+    return method
+
 def xmpp_date(timestamp=None, with_time=True):
     """Return date according to XEP-0082 specification
 
@@ -61,6 +87,7 @@
     """Parse a date and return corresponding unix timestamp
 
     @param value(unicode): date to parse, in any format supported by dateutil.parser
+    @return (int): timestamp
     """
     return calendar.timegm(dateutil.parser.parse(unicode(value)).utctimetuple())