0

I'm trying to create a proxy (wrapper) object so I can modify behaviour of an already instantiated object. Attributes of a wrapper class are set to a newly generated class (using type) along with attributes of an underlying object, it's done this way because Python __magic __ methods work correctly only if they are members of a class. So cls is a wrapper class, client is the underlying object:

def __new__(cls, client, *args, **kwargs):
    ns = {}
    for i, attr in inspect.getmembers(client):
        if i in ('__init__', '__new__', '__getattribute__', '__dict__'):
            continue
        ns[i] = attr
    for i in cls.__dict__:
        if i in ('__new__',):
            continue
        elif i == '__init__':
            ns['_init_'] = getattr(cls, i)
            continue
        attr = getattr(cls, i)
        ns[i] = attr
    P = type(cls.__name__ + "." + client.__class__.__name__,
             (Proxy2.BaseProxy,), ns)
    P._client_ = client
    return P(*args, **kwargs)

The problem comes from @staticmethod/@classmethod in the wrapper class. I cannot call static method from an instance because self is being passed to it. I've tried to use __get__ but without success. Here's a minimal example which fails:

class SuperA:
    @staticmethod
    def static():
        return 'static?'

class A:
    def __getattribute__(self, attr):
        v = object.__getattribute__(self, attr)
        if hasattr(v, '__get__'):
            v2 = v.__get__(None, self)
            return v2
        return v

A.static = getattr(SuperA, "static")
print(A.static())  # success
print(A().static())  # fail
Winand
  • 2,093
  • 3
  • 28
  • 48

1 Answers1

0

Instead of getattr which invokes descriptors mechanism inspect.getattr_static can be used like this:

A.static = inspect.getattr_static(SuperA, "static")
Winand
  • 2,093
  • 3
  • 28
  • 48