Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: calling function from imported file

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...

like image 607
RageCage Avatar asked Sep 27 '13 16:09

RageCage


People also ask

How do you use a function from an imported module in Python?

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.

How do you call a function from another file in Python?

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.

Can Python functions be external files?

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.


1 Answers

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()
like image 88
Martijn Pieters Avatar answered Sep 26 '22 18:09

Martijn Pieters