For a school project about artificial intelligence, I need to be able to connect a function name to another function like this for example:
def b_test(x):
return x+1
def a_test(x):
return x
variable = "b"
variable+= "_test"
a_test = variable
I guess that Python wants to use the name “b” as the new name/alias of the function a_test instead of using b_test as the new name.
So how can I force python to look what b means instead of just using it?
EDIT:
What I want to do is :
I have in my variable variable
the string b
and I need to, when I use in my code a_test(x)
, return x+1 (the return of the function b_test
). So I add the string “_test” to variable so it is “b_test”.
I could do it by coding
a_test = b_test
but I won’t only connect a_test to b_test, it might be c_test or d_test, that’s why I need to use a variable.
2
Answers
Your example should work actually, but it doesn’t reflect your actual code and error from the screenshot. In your screenshot, you are trying to get the ChosenFunction from mlp_functions module, which does not have that attribute, hence the AttributeError. To get the attribute from a module using a str name, you would need to use
getattr
like:First of all you need to construct the function name (from your variable) and retrieve the module name so you can load the python function object in the variable you need.
Here is the code:
Some important notes:
test
variable that points to the correct function to executegetattr
function is a little bit tricky with file names and modules so if you modify this code you maybe want to modify the way the function module is computed.