You should first understand how Python imports work a little.
The first time you invoke import
on a module, it gets executed. The resulting namespace, with all function and variable definitions is used to create a module object that is referenced in your namespace, as well as in sys.modules
. The next time it gets imported, the import just references the existing module from sys.modules
.
To avoid errors caused by cyclic imports, the module object is actually created first, before the code is run, so that further imports will already see an existing module in sys.modules
and not attempt to re-execute the same code over and over.
In your particular case, you need to explicitly import define_cmd2
from define_cmd1
if you want to use the contents of define_cmd1
. Secondly, you need to reference the imported names properly:
define_cmd1:
def cmd1():
print("calling cmd1")
import define_cmd2
define_cmd2.cmd2()
define_cmd2
import define_cmd1
import define_cmd1.cmd1()
def cmd2():
print("called cmd2")
The bolded items are bits of code you need to add.
To clarify, here is what will happen when you run define_cmd
:
- The
def
statement will create a function define_cmd1.cmd1
.
- The
import
will attempt to load define_cmd2
- The
import
in define_cmd2
will do nothing since sys.modules['define_cmd1']
already exists, meaning that it is loaded or being loaded.
define_cmd1.cmd1()
will run.
- The
def
statement will create a function define_cmd2.cmd2
- Return to loading
define_cmd1
- Run
define_cmd2.cmd2