0

I would like to add methods in a class that have the same signature and trigger their call from a parent method like shown below. This example works:

class A:
    def call_others(self, settings):
        switch = {'add': self.action_add, 'remove': self.action_remove}
        for key in settings:
            switch[key](settings[key])
   
    def action_add(self, settings):
        pass

    def action_remove(self, settings):
        pass

But now I would like to create automatically the switch dict by retrieving the action functions and call them with exec like this:

class A:
    def call_others(self, settings):
        
        prefix = 'action_'
        actions = [func[len(prefix):] for func in dir(self) if func.startswith(prefix)]

        switch = dict()
        for action in actions:
            switch[action] = 'self.'+prefix+action

        for key in settings:
            exec(switch[key](settings[key]))
   
    def action_add(self, settings):
        pass

    def action_remove(self, settings):
        pass

In this example, exec(switch[key](settings[key])) does not work, exec expects a str and I can't see how to supply the settings[key] argument.

settings example is given here:

settings = {'add': [1, 2, 3, 4], 'remove': {'condition': True, 'number': 5}}

Thanks for your help!

1 Answer 1

1

You don't need exec.

for action in actions:
    switch[action] = getattr(self, prefix + action)

for key in settings:
    switch[key](settings[key])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.