1

Got 2 files:

First is called: main.py

import side

var = 1

side.todo()

Second is called: side.py

import main


def todo():
    print "printing variable from MAIN: %s" %(main.var)

I get an error, when i run main.py:

AttributeError: 'module' object has no attribute 'todo'

In python are you not allowed to borrow and use variables, in such manner?

I have tried to search for documentation related to this, but could not find anything related to this problem.

Surely, there is an alternate way of doing this?

mrdigital
  • 79
  • 1
  • 9
  • 5
    You have cyclic imports. See here for explanation: [Python: Circular (or cyclic) imports](http://stackoverflow.com/a/744403/222914) – Janne Karila Oct 06 '12 at 18:54
  • Yes I understand now that cyclic loops between modules are not allowed. So is there any way to overcome this problem? besides putting everything under one source file. – mrdigital Oct 06 '12 at 19:00
  • @mrdigital: It's more nuanced than that. Cyclic imports between modules *are* allowed, but you have to be careful when you do it. In your case, you'll want to replace every instance `main` with `__main__` in `side.py`. – icktoofay Oct 06 '12 at 19:03
  • @icktoofay: That was brilliant, it works! ofcourse, it makes sense – mrdigital Oct 06 '12 at 19:10

2 Answers2

2

The problem is not "you can't have cyclic imports", it's that you can't use a name before it's defined. Move the call to side.todo() somewhere it won't happen as soon as the script is run, or move main.var into a third module.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

A fast and ugly solution is to move the import statement to where it will not be executed until it is needed in side.py

def todo():
    import main
    print "printing variable from MAIN: %s" %(main.var)

I would advice against it though. The example is contrived, but I'm sure you can find a nicer solution to your specific case.

Johanna Larsson
  • 10,531
  • 6
  • 39
  • 50