OK 400
OK 400

Reputation: 831

Circular imports on Python

Well, I'm trying to set up fileA which has functions from fileB. Inside file B i use some variables from file A. It's something like this:

fileA
import fileB
a = []
fileB.function1()

and file B is:

fileB
import fileA
def function1():
 fileA.a.extend([2, 3])

but i get this error:

AttributeError: module 'fileB' has no attribute 'function1'

I know there are multpiles question about the same thing, but i have not seen anyone having an error like this, and until now I'm unable to find a solution

Upvotes: 2

Views: 103

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

@brunodesthuilliers how would you do avoid circular dependencies in this case?

I'd first question why f1 wants to call a function in f2 that wants to touch a variable in f1. Since all we have here is a toy example out of any context, it's impossible to give a one-size-fits-all answer, but there are at least three main solutions:

 1. move f2.function back into f1.

If both need to know each other so intimately, why separate them ?

f1.py:

def function():
   a.extend([2, 3, 4]])

a = []

f2.py

import f1
f1.function()
print(f1.a)

 2. move the call to f2.function in another module f3

so f1 doesn't have to know about f2.

f1.py

a = []

f2.py

import f1

def function():
   f1.a.extend([2, 3, 4]])

f3.py

import f1
import f2

# this is really ugly... spooky action at distance.
f2.function()
print(f1.a)

3. change f2.function so it takes a as argument

so f2 doesn't have to know about f1

f1.py

import f2
a = []
f2.function(a)

f2.py

def function(a):
    a.append([2, 3, 4])

Upvotes: 1

Janekx
Janekx

Reputation: 641

You can use local imports in this case instead of global ones. I've seen many of this in the source code of OpenStack.

f1.py

import f2
a = []
f2.function1()

f2.py

def function1():
  import f1
  f1.a.extend([2, 3])

Upvotes: 2

Related Questions