Mostly well-known, here's how to call a super class's overloaded method f.
class Base:
def f(self, *args):
print(f"BASE method invoked.")
class Inherit(Base):
def f(self, *args):
super(Inherit, self).f(*args) # Calling overloaded method
However, if I don't know f, and instead, it's passed as an argument func, how shall I rewrite the super... statement? An example context is to define a decorator that applies some uniform operation to all the overloaded functions.
Clarification and more details:
In the following example, I have a Base class that is a library not owned by me. It has severals (20+) methods f, g etc that internally makes some remote procedure calls (RPC). The library documentation suggests subclassing the Base to use it.
For debugging purpose, I would like to record a log every time a RPC is called. So I'd like to make a uniform function decorator log_rpc for all the RPC methods.
def log_rpc(func):
"""This does not work"""
def new_func(self, *args, **kwargs):
print(f"Invoking RPC {METHODNAME} with parameters: {locals()}")
super(CLASSNAME, self).METHODNAME(*args, **kwargs) # Two issues here.
return new_func
class Base: # This is provided by some library
def f(self, *args):
# rpc_client.f() # make some rpc calls.
print(f"BASE method invoked.")
def g(self, *args):
# rpc_client.g() # make some rpc calls.
print(f"BASE method invoked.")
class Inherit(Base): # My own code subclassing the library
@log_rpc
def f(self, *args):
"""function body will be ignored by the decorator."""
pass
@log_rpc
def g(self, *args):
"""function body will be ignored by the decorator."""
pass
Inherit().f()
However, when making a generic decorator independent of Inherit class or method f, there are two emerging issues
- How do I figure out the
CLASSNAMEin the decorator? Since the decorator is invoked during the classInheritis being constructed, I can't use module's__qualname__to retrieve theInheritclass object. - How do I figure out the
METHODNAMEin the decorator?
What I have searched so far:
- A similar question thread but does not have a solution.
- Python documentation about
superand descriptor mechanism.