Python: calling function from imported file
Question: 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...


Answer: 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()
    

