Home > Back-end >  Best way to forward/redirect methods/attributes in python class without redundant code/docstrings?
Best way to forward/redirect methods/attributes in python class without redundant code/docstrings?

Time:10-05

I have a project, with some modules each of which contains a class doing their respective thing. Then I have an API class for the user. The API class instantiate those classes, and should forward/redirect to those who are doing the actual processing. I have the following questions:

  1. How do I do the forwarding without rewriting what seems to me redundant code? For example, say Foo is the API class, Bar is a module class, then now I am writing something like:

    class Foo:
        def __init__(self, bar: Bar):
            self.bar = bar
        def name(self):
            return self.bar.name()
    

    I explicitly wrote name method in Foo, which just returns name() of Bar. Isn't this redundant? Is there an "automatic" way to forward the call?

  2. In the bar class I'd write some docstrings. Is there a way to "port" these docstrings to the API class Foo? Writing them again in Foo would be redundant and difficult to maintain.

CodePudding user response:

You can assign bar.name to self.name. Same goes for the docstring with the __doc__ attribute of the class:

class Foo:
    def __init__(self, bar: Bar):
        self.bar = bar
        self.name = bar.name
        self.__class__.__doc__ = bar.__class__.__doc__

CodePudding user response:

Try redirecting the __getattr__ magic method:

class Foo:
    def __init__(self, bar: Bar):
        self.bar = bar
    def __getattr__(self, attr):
        return getattr(self.bar, attr)

This would redirect all functions to the bar variable.

For multiple classes:

class Foo:
    def __init__(self, bar: Bar, foo: Foo, blah: Blah):
        self.bar = bar
        self.foo = foo
        self.blah = blah
    def __getattr__(self, attr):
        if hasattr(self.bar, attr):
            return getattr(self.bar, attr)
        elif hasattr(self.foo, attr):
            return getattr(self.foo, attr)
        else:
            return getattr(self.blah, attr)
  • Related