I have a simple class in which I want to generate methods based on inherited class fields:
class Parent:
def __init__(self, *args, **kwargs):
self.fields = getattr(self, 'TOGGLEABLE')
self.generate_methods()
def _toggle(self, instance):
print(self, instance) # Prints correctly
# Here I need to have the caller method, which is:
# toggle_following()
def generate_methods(self):
for field_name in self.fields:
setattr(self, f'toggle_{field_name}', self._toggle)
class Child(Parent):
following = ['a', 'b', 'c']
TOGGLEABLE = ('following',)
At this moment, there is a toggle_following
function successfully generated in Child
.
Then I invoke it with a single parameter:
>>> child = Child()
>>> child.toggle_following('b')
<__main__.Child object at 0x104d21b70> b
And it prints out the expected result in the print
statement.
But I need to receive the caller name toggle_following
in my generic _toggle
function.
I've tried using the inspect
module, but it seems that it has a different purpose regarding function inspection.