I've written a program (A) that takes, as input, the names of functions I wrote in a separate program (B). I want to use these functions in program (A), so I am trying to run (A) by doing this: A(f1, f2, f3, f4)
At the top of (A), I imported program (B) using import B. In (A) there is just one function (excluding main) that accepts four inputs (f1, f2, f3, f4), and then uses them, like this:
for i in range(x, y):
z = B.f1(i)
u = B.f2(i)
...
...
The trouble is, when I try to run A(f1, f2, f3, f4), I get the error
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
A(f1, f2, f3, f4)
NameError: name 'f1' is not defined
I see that python is not recognizing the functions in (B) as input in (A), but I don't know why or how else I can connect the two programs.
Update: Program A
def A(f1, f2, f3, f4) :
x = 0
y = 10
for i in range(x, y):
x = B.f1(i) //returns float
plt.plot(i, x)
...
3 Answers 3
Based on a literal reading of your question, if you imported B via
import B
then every reference to functions, variables, classes etc defined in B must be done in the form B.func1 etc.
Your error message clearly says that you're trying to do A(f1, f2, f3, f4). This should be A(B.f1, B.f2, B.f3, B.f4)
EDIT Judging from your updated question, I'm guessing you want something like:
import B
def A(input_function1, input_function2, input_function3, input_function4) :
x = 0
y = 10
for i in range(x, y): #btw, you don't need the x value here if it's 0
x = input_function1(i) //returns float #I removed the 'B.'
plt.plot(i, x)
# Other stuff here
if __name__=='__main__':
A(B.f1, B.f2, B.f3, B.f4)
# or alternatively A(B.f78, B.f21, B.f1, B.f90) or whatever
Or alternatively:
from B import f1, f2, f3, f4
def A(f1, f2, f3, f4) :
# Stuff here
if __name__=='__main__':
A(f1, f2, f3, f4) # Explicit imports mean that the 'B.' prefix is unnecessary
3 Comments
A, it'll use the local f1 f2 f3 and f4. Outside it'll use the imported ones. Name them something else to prevent confusion.To extend what @zehnpaard has already suggested, if you want to call the B function in A() using f1...f4 as arguments, you can alternatively use getattr(), like this:
...
def A(f1, f2, f3, f4) :
x = 0
y = 10
for i in range(x, y):
x = getattr(B, f1)(i)
plt.plot(i, x)
...
getattr(B, f1) will return the function as in B.f1, and you call the function and pass the argument i with (i), just like: getattr(module, function)(*args).
For example: getattr(plt, 'plot')(i, x) = plt.plot(i, x)
Pay attention that you pass plot as string 'plot', so when you're trying to call function A(), you will do:
if __name__=='__main__':
A('f62', 'f22', 'f2323', 'f100')
As a side note: if the function you pass is not in B, it will raise AttributeError.
Hope this helps.
Comments
Sounds like you have the following defined in your interactive session
import B
def A(f1, f2, f3, f4):
for i in range(10):
plt.plot(i, f1(i))
And the user should call it by doing:
>>> A(B.f1, B.f49, B.f100, B.f42)
A(from terminal, I assume?)