Python: calling a function from an imported file

How do you call a function from an imported file? eg:

Test:

import test2 def aFunction(): print "hi there" 

Test2:

 import test aFunction() 

This gives me a name error saying that my function is undefined. I also tried:

 from test import aFunction 

and

 from test import * 

I also did not try to import test2 into the test. I come in Python with C ++, so I'm afraid that I am missing something obviously obvious for Python veterans progammers ...

+8
python
source share
1 answer

Loop import is created. test.py imports test2.py , which attempts to import test.py

Do not do this. By the time test2 imports test , this module has not completed the execution of all the code; function not yet defined:

  • test compiled and executed, and an empty module object is added to sys.modules .

  • The line import test2 .

    • test2 compiled and executed, and an empty module object is added to sys.modules .

    • The line import test .

      • test already present as a module in sys.modules , this object is returned and attached to the name test .
    • The next line tries to run test.aFunction() . There is no such name in test . The exception is fixed.

  • Lines def aFunction() are never executed because an exception was thrown.

Delete the line import test2 and run test2.py directly, and importing the function will work fine:

 import test test.aFunction() 
+9
source share

All Articles