2

I'm just curious why all examples of proxy-pattern written in Python are using composition over inheritance? If proxy class should implement all of the methods of original class, isn't it easier to inherit proxy from original and just overwrite methods we want to perform additional logic (caching, logging, etc.), using super().method()?

The relationship between classes is also respected: the proxy class is some kind of an original class.

Example:

class Original:
    def some_method(self):
        return "some"

    def another_method(self):
        return "another"

class Proxy(Original):
    def another_method(self):
        res = super().another_method()
        logger.log(res)

        return res
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
kit4
  • 21
  • 2

1 Answers1

1

Lets take a look at one of the "classical" diagrams for proxy pattern (from wiki):

enter image description here

I would argue that "If proxy class should implement all of the methods of original class" statement is not true - the proxy class should implement all of the "contract" methods (Subject interface) and it hides the implementation detail i.e. RealSubject from the user (also RealSubject potentially can have some other public methods not defined by the interface).

One more thing to consider - composition can give the proxy ability to control the lifetime of the proxied class instance, while with inheritance (if we skip the fact that there is no more "proxying" happening) it is not possible for the "proxy" itself.

Also note that there are benefits (and drawbacks) in choosing composition over inheritance in general.

Some more useful reading:

  1. Prefer composition over inheritance? SO answer
  2. Differences between Proxy and Decorator Pattern
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thanks, I got the point that there is more lifetime control of the proxied class instance, but I also found this (https://refactoring.guru/design-patterns/proxy/python/example): "In real life, however, clients mostly work with their real subjects directly. In this case, to implement the pattern more easily, you can extend your proxy from the real subject's class". It looks like sometimes it is an ok-decision to use inheritance, but the question is, can we still call it a proxy-pattern. – kit4 Sep 25 '22 at 12:04
  • 1
    @kit4 I would argue that no. But it's ok, as any pattern it's used to solve some concrete problems with some concrete approach and it is no applicable to all similar situations. If you have one-to-one mapping between the "proxy" and the proxied class and access/lifetime is not a concern and there are no other things to consider - it can be ok to use simple inheritance to extend the functionality without introducing more complicated concepts. – Guru Stron Sep 25 '22 at 12:50