How do you call a function from an imported file? for example:
Test:
import test2
def aFunction():
print "hi there"
Test2:
import test
aFunction()
This give me a name error, saying my function isn't defined. I've also tried:
from test import aFunction
And:
from test import *
I've also tried not importing test2 in test. I'm coming to Python from C++, so I fear I'm missing something blatantly obvious to veteran Python progammers...
You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.
To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.
User-defined functions can be called from other files. A function can be called and run in a different file than the file where the function is defined.
You are creating a circular import. test.py
imports test2.py
which tries to import test.py
.
Don't do this. By the time test2
imports test
, that module has not completed executing all the code; the function is not yet defined:
test
is compiled and executed, and an empty module object is added to sys.modules
.
The line import test2
is run.
test2
is compiled and executed, and an empty module object is added to sys.modules
.
The line import test
is run.
test
is already present as a module in sys.modules
, this object is returned and bound to the name test
.A next line tries to run test.aFunction()
. No such name exists in test
. An exception is raised.
The lines defining def aFunction()
are never executed, because an exception was raised.
Remove the import test2
line, and run test2.py
directly, and importing the function will work fine:
import test
test.aFunction()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With