tags:

views:

50

answers:

2

Using a class that has an xmlrpc proxy as one of it's object's properties

def __init__(self):
    self.proxy = ServerProxy(...)
    # ...

I'm trying to ease the use of some of the proxy's functions. Only a subset of the proxy functions are supposed to be used and I thus thought of creating a set of tiny wrapper functions for them like

def sample(self):
    """ A nice docstring for a wrapper function. """
    self.proxy.sample()

Is there a good way of getting a list of all the wrapper functions? I'm thinking about something like dir(), but then I would need to filter for the object's wrapper functions. xmlrpc introspection (http://xmlrpc-c.sourceforge.net/introspection.html) doesn't help much either since I don't want to use/ provide all the server's functions.

Maybe setting an attribute on the wrappers together with a @staticmethod get_wrappers() would do the trick. Having a _wrapper suffix is not appropriate for my use case. A static list in the class that keeps track of the available is too error prone. So I'm looking for good ideas on how to best getting a list of the wrapper functions?

+3  A: 

I'm not 100% sure if this is what you want, but it works:

def proxy_wrapper(name, docstring):
    def wrapper(self, *args, **kwargs):
        return self.proxy.__getattribute__(name)(*args, **kwargs)
    wrapper.__doc__ = docstring
    wrapper._is_wrapper = True
    return wrapper

class Something(object):
    def __init__(self):
        self.proxy = {}

    @classmethod
    def get_proxy_wrappers(cls):
        return [m for m in dir(cls) if hasattr(getattr(cls, m), "_is_wrapper")]

    update = proxy_wrapper("update", "wraps the proxy's update() method")
    proxy_keys = proxy_wrapper("keys", "wraps the proxy's keys() method")    

Then

>>> a = Something()
>>> print a.proxy
{}
>>> a.update({1: 42})
>>> print a.proxy
{1: 42}
>>> a.update({"foo": "bar"})
>>> print a.proxy_keys()
[1, 'foo']
>>> print a.get_proxy_wrappers()
['proxy_keys', 'update']
balpha
Thanks, this looks just right. I'll try it out on Monday :)
Gerald Senarclens de Grancy
+2  A: 

Use xml-rpc introspection to get the server list and intersect it with your object's properties. Something like:

loc = dir(self)
rem = proxy.listMethods() # However introspection gets a method list
wrapped = [x for x in rem if x in loc]