ILostMySpoon
ILostMySpoon

Reputation: 2409

Issue with importing specific functions from modules

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

Upvotes: 0

Views: 57

Answers (2)

glglgl
glglgl

Reputation: 91017

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.

Upvotes: 0

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18457

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.

Upvotes: 2

Related Questions