4

From Python in a Nutshell

super(cls,obj) returns a super-object of object obj (which must be an instance of class cls or of any subclass of cls), suitable for calling superclass methods.

From https://docs.python.org/3.6/library/functions.html#super

super([type[, object-or-type]]) returns a proxy object that delegates method calls to a parent or sibling class of type.

A comment by Martijn Pieters says that the return object of super(cls,obj) is an example of the proxy design pattern.

In Design Pattern by Gamma et al, the proxy design pattern is implemented by inheriting the class of the subject of proxy.

enter image description here

But I found that super class is inherited only from object, and not from the subject of proxy, which is "a parent or sibling class of type". So I wonder how the super class implement the proxy design pattern? By duck typing?

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590

1 Answers1

1

It just customizes the dunder method __getattribute__: all attribute retrieval from the super object is customized, and respects the __mro__ of the class the super object was created for.

That means: the Python language has no need to actually inherit from a type one is proxing to offer access to its attributes. Attribute access can be fully customized using different mechanisms, that redirect whatever attributes one wants proxied to the original class. Customizing __getattribute__ is likely the "stronger" of the attribute access customizations, but there are also __getattr__ or using descriptors.

So, answering further - my understanding of "duck typing" is an object which class presents a minimal set of attributes and methods to "look like" another object when it tries to be used like that other object. Under this view, one can say that super does use duck typing, as upon trying to retrieve methods and attributes from the super object, those will be fetched from the proxied type.

However, the super class won't try to mimick the proxied type in it's repr or be instrospectable in the usual ways Python objects are (by using dir or checking the object's __dict__). But since duck typing does not require that either, it just has to work as the original object for the desired purposes, which usually is to fetch and call a method with a hardcoded name. So, yes, "duck typing".

Note that if it was needed, Python customization capabilities would go as far as to allow "super" to return "True" to a call from issubclass on the proxied class. (it does not, because there is no need as noted above).

jsbueno
  • 99,910
  • 10
  • 151
  • 209