Access to a subset of Python class functions

Using a class with xmlrpc proxy as one of the object properties

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

I am trying to facilitate the use of some proxy features. It is assumed that only a subset of proxy functions will be used, and therefore I thought about creating a set of tiny wrapper functions for them, for example

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

Is there a good way to get a list of all shell functions? I am thinking of something like dir (), but then I will need to filter the wrapper functions of the object. Introspection xmlrpc ( http://xmlrpc-c.sourceforge.net/introspection.html ) does not help much, because I do not want to use / provide all the server functions.

Perhaps setting the attribute on the wrappers along with the @staticmethod get_wrappers () method will do the trick. Having the _wrapper suffix is ​​not suitable for my use case. A static list in a class that monitors availability is too error prone. So I'm looking for good ideas on how best to get a list of wrapper functions?

+3
source share
2 answers

I am 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 update() method")
    proxy_keys = proxy_wrapper("keys", "wraps the proxy 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']
+3
source

Use xml-rpc introspection to get a list of servers and cross it with your object properties. Sort of:

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

Source: https://habr.com/ru/post/1731677/


All Articles