Accessing static fields from the decorated class

180 Views Asked by At

Full code example:

def decorator(class_):
    class Wrapper:
        def __init__(self, *args, **kwargs):
            self.instance = class_(*args, **kwargs)

        @classmethod
        def __getattr__(cls, attr):
            return getattr(class_, attr)
    return Wrapper


@decorator
class ClassTest:

    static_var = "some value"


class TestSomething:

    def test_decorator(self):
        print(ClassTest.static_var)
        assert True

When trying to execute test, getting error:

test/test_Framework.py F
test/test_Framework.py:37 (TestSomething.test_decorator)
self = <test_Framework.TestSomething object at 0x10ce3ceb8>

    def test_decorator(self):
>       print(ClassTest.static_var)
E       AttributeError: type object 'Wrapper' has no attribute 'static_var'

Is it possible to access static fields from the decorated class?

2

There are 2 best solutions below

2
On BEST ANSWER

While the answer from @martineau probably better addresses the specific issue you are trying to solve, the more general approach might be to use create a metaclass in order to redefine the instance method __getattr__ on a type instance (and classes are instances of type).

def decorator(class_):
    class WrapperMeta(type):
        def __getattr__(self, attr):
            return getattr(class_, attr)

    class Wrapper(metaclass=WrapperMeta):
        def __init__(self, *args, **kwargs):
            self.instance = class_(*args, **kwargs)

    return Wrapper

This allows the attribute look-up on the class itself to be passed through WrapperMeta.__getattr__.

7
On

You can get it to work by making the decorator create a class derived from the one being decorated.

Here's what I mean:

def decorator(class_):
    class Wrapper(class_):
        def __init__(self, *args, **kwargs):
            self.instance = super().__init__(*args, **kwargs)

    return Wrapper

@decorator
class ClassTest:
    static_var = "some value"

print(ClassTest.static_var)  # -> some value