0

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

8
  • What does not works mean? Do you get an ImportError? Commented Feb 19, 2014 at 9:22
  • 1
    Both names should throw an exception; you have a circular import, don't do that. Move both myInt and myFunction to a separate nested module. Commented Feb 19, 2014 at 9:26
  • Can you provide runnable code that demonstrates the error when run? myfile isn't runnable, and I don't think it would produce the error you've posted if you removed the ... (though I haven't tested it yet). Commented Feb 19, 2014 at 9:27
  • @user2357112: The code posted demonstrates the error. Commented Feb 19, 2014 at 9:31
  • I removed everything but the lines I have in my question and I have the same mistake. But in fact, I think @Martijn Pieters is right about the circular import. I need to move the function to a separate module or remove the include import mymodule.myfile from the __init__.py file. Commented Feb 19, 2014 at 9:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.