I assume that the actual problem is more complex than a simple string comparison to find the function, but for the sake of clarity my first example uses the simplified case.
If you treat B as a module that you can import, using the built-in, vars()
, you could iterate over the names of functions and the functions themselves in parallel and test for the condition and execute.
import B
for name, value in vars(B).items():
if name == 'functionOne':
value()
vars()
is a built-in similar to dir()
except that it returns a dictionary of the names and values. If you used dir()
, you'd have to then use getattr()
or B.__dict__[name]
or some other extra step to get the value.
A more general implementation could look like:
for name, value in vars(B).items():
if callable(value) and check_conditions_met(name, value):
value()
You would need to declare and implement check_conditions_met()
. value()
invokes the function without parameters.
The for
loop iterates over the name
of each member of the module, and its value
. callable()
will be true if the value
can be called as a function.
If you already know the names of the functions you want to execute in a module and they don't vary, but may not be implemented:
try:
B.functionOne()
except AttributeError as ae:
print(f"module 'B' may be missing an implementation: {ae}")
You can always get an attribute of any object by name using getattr()
:
getattr(B, 'functionOne')()
Kind of a roundabout way of going about it though. But could be useful for the case where user input (as suggested in another answer) is used to select the function to run:
for _ in range(n_attempts):
try:
request = input("What do you want me to do? ")
cmd, *params = request.split()
getattr(B, cmd)(*params)
except AttributeError:
print("Please try again...")