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?

4
  • 5
    You have cyclic imports. See here for explanation: Python: Circular (or cyclic) imports Commented Oct 6, 2012 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. Commented Oct 6, 2012 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. Commented Oct 6, 2012 at 19:03
  • @icktoofay: That was brilliant, it works! ofcourse, it makes sense Commented Oct 6, 2012 at 19:10

2 Answers 2

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.

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

Comments

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.

1 Comment

I have tried that before on a similar problem, but it did not work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.