Python: Convert str format to callable method

Viewed 1459

I do not quite know what to google to find a solution for my problem so I will try to find it here.

I am creating a Gui in Python 3.5.2 with pygame. I am currenctly working on Error popups that have a different button function depending on the error that is popping up. I want to give the function that is supposed to be executed as an argument in another class.

Code looks something like this:

def i_want_to_call_this(self):
  print("Button works.")

def button_with_action(self, action):
    self.button(self.action)

The other class will give the argument for which function the button will have like this:

popup_instance.popup_with_action(i_want_to_call_this)

The problem however is that the argument is parsed into string format and is not callable.

1 Answers

I do not know what the methode button does (I guess that it binds to a given button the callable that is passed as argument), but you should consider using getattr, to be able to call a function by using its name, passed as string, as follows

def button_with_action(self, action):
    dyn_created_callable = getattr(self, action)
    self.button(dyn_created_callable)

Of course nothing stops you from doing directly

def button_with_action(self, action):
    self.button(getattr(self, action))

That you would then use by doing

#...
    self.button_with_action('i_want_to_call_this')
Related