I have two separate modules that I am trying to import specific functions into each other however I keep getting an import error on the functions that are defined within the helperModule.py module itself. What am I doing wrong?
helperModule.py
from utilsModule import startProcess
def getCfgStr():
pass
def getCfgBool():
pass
def doSomethingElse():
startProcess()
utilsModule.py
from helperModule import getCfgStr, getCfgBool
def startProcess():
a = getCfgStr()
b = getCfgBool()
pass
2 Answers 2
You show:
from utilsModule import startProcess
which corresponds to your utilsModule.py where the startProcess function is defined. At the top of that file, you show:
from helperModule import getCfgStr, getCfgBool
which corresponds to your helperModule.py where these two functions are defined.
This is a circular import. utilsModule imports from utilshelperModule which imports from utilsModule... you see where I'm going.
You must refactor and have them both import from a third file to prevent this.
Comments
You could either have the functions need the functions they need (on runtime instead of on load time):
def getCfgStr():
pass
def getCfgBool():
pass
def doSomethingElse():
from utilsModule import startProcess
startProcess()
def startProcess():
from helperModule import getCfgStr, getCfgBool
a = getCfgStr()
b = getCfgBool()
Or you at least could do the imports as late as possible:
def getCfgStr():
pass
def getCfgBool():
pass
def doSomethingElse():
startProcess()
from utilsModule import startProcess
and
def startProcess():
a = getCfgStr()
b = getCfgBool()
from helperModule import getCfgStr, getCfgBool
Here, we first put the functions into existence and then provide their global name space with the functions from the other module.
This way, a circular import will probably work, because the imports happen late.
It will nevertheless work, as long as none of the functions affected is used at import time.
helperModule.pybut your second imports from a module calledutilshelperModule. So is this a case of a circular import error being hidden by a typo, or did you misreport the name of your files? (Since you only described the error instead of copy-pasting the actual error, it's hard to distinguish between the two.)