Search code examples
pythonpython-3.xtagsdecorator

Run class method based on tag


I wanted to run the below class functions based on tag name provided at run time

def tag(tag_name):
    def tags_decorator(func):
        func._tag = tag_name
        return func

    return tags_decorator


class ExampleClass:
    @tag('foo')
    def method_a(self):
        print(" method_a foo")

    @tag('bar')
    def method_b(self):
        print(" method_b bar")

    def method_c(self):
        print(" method_c")

Expectation:

if __name__ == '__main__':
    ec = ExampleClass()
    ec.foo # it should run the method tagged with foo i.e. method_a and should
           # print " method_a foo"

Solution

  • That seems like a weird requirement but you can implement __getattr__ to realize it:

    class ExampleClass:
        ...
    
        def __getattr__(self, name):
            for tp in type(self).mro():
                for obj in vars(tp).values():
                    if getattr(obj, '_tag', None) == name:
                        return obj(self)
            raise AttributeError(name)