Question

I have a module like below and I want to include a function from __init__.py in myfile.py

/mymodule
   /__init__.py
   /myfile.py

The init is

import mymodule.myfile

myInt = 5

def myFunction():
    print "hey"

and the myfile file

from mymodule import myFunction
from mymodule import myInt
...

So the myInt include works but not the myFunction one. Do you have an idea why?

Thanks

EDIT

The error message is ImportError: cannot import name myFunction

Was it helpful?

Solution

You have a circular import:

  • myInt and myFunction have not yet been assigned to when the import mymodule.myfile is run.
  • mymodule.myfile then tries to import the names that are not yet assigned to from mymodule.

Your options are to move myInt and myFunction to a separate shared module:

mymodule/
    __init__.py
    myfile.py
    utilities.py

where __init__.py imports from both mymodule.myfile and mymodule.utilities, and myfile.py imports from mymodule.utilities.

Or you can import just the module in myfile.py and defer referencing the myInt and myFunction names until later (in a function call, for example):

import mymodule

def somefunction():
    mymodule.myFunction(mymodule.myInt)

By the time somefunction() is called all imports have completed and mymodule.myFunction and mymodule.myInt have been assigned to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top