diff pyloader/invoke.py @ 5:a825f00fe062

add a different call method, rename the old one, and have a test for it
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 19 May 2011 12:26:29 -0700
parents 5ce55f6c8964
children efb7a8a189e8
line wrap: on
line diff
--- a/pyloader/invoke.py	Tue May 10 19:00:57 2011 -0700
+++ b/pyloader/invoke.py	Thu May 19 12:26:29 2011 -0700
@@ -3,7 +3,7 @@
 from cast import cast
 from cast import str2args
 
-def call(obj, *args, **kwargs):
+def strcall(obj, *args, **kwargs):
     """call a thing with string arguments"""
     inspected = obj
     if inspect.isclass(obj):
@@ -21,6 +21,23 @@
         kwargs = dict([(key, cast(value)) for key, value in kwargs.items()])
     return obj(*args, **kwargs)
 
+def call(obj, **kwargs):
+    """
+    call an object with the subset of kwargs appropriate to the object.
+    this assumes that the obj does not take **kwargs
+    """
+    inspected = obj
+    if inspect.isclass(obj):
+        inspected = obj.__init__ # inspect the ctor
+        args = inspect.getargspec(inspected).args[1:]
+    else:
+        args = inspect.getargspec(obj).args[:]
+    kw = {} # kwargs to invoke obj with
+    for arg in args:
+        if arg in kwargs:
+            kw[arg] = kwargs[arg]
+    return obj(**kw)
+
 def main(args=sys.argv[1:]):
     """CLI entry point"""
     from loader import load
@@ -33,7 +50,7 @@
         parser.exit()
     obj = load(args[0])
     obj_args, obj_kwargs = str2args(' '.join(args[1:]))
-    print call(obj, *obj_args, **obj_kwargs)
+    print strcall(obj, *obj_args, **obj_kwargs)
 
 if __name__ == '__main__':
     main()