Njubster
Njubster

Reputation: 69

Communication between two Python files

I'm having a problem with importing files which can be simplified as this:

a.py:

import b

a = 0
b.foo()

b.py:

import a

def foo():
    a.a=4

So, what I'm trying to do is: in file a.py call the function foo() from b.py which would then change the value of a variable that is in a.py. This is the error I get:

AttributeError: module 'b' has no attribute 'foo'

What am I doing wrong? What would be the proper way to do this?

Upvotes: 0

Views: 5861

Answers (2)

Hara
Hara

Reputation: 1502

First and foremost thing is making circular import, and fixing it is not a good idea.

But try to do small change in your code and solve.

a.py:

from b import foo

a = 0
foo()
print a

b.py:

def foo():
    import a as filea
    filea.a=4

when you run a.py, watch the print a, it is executing two times. You need to be at your own risk by fixing lot of such things. Instead of doing all circus, better to avoid circular import.

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46859

your import is circular. you need to come up with a way of testing that with a non-circular import. e.g. create a new main file that you execute; import a.a and b.foo there:

main.py

from b import foo
import a

a.a = 7
foo()

a.py

a = 0

b.py

import a

def foo():
    a.a=4

Upvotes: 2

Related Questions