0

I am encountering a problem using a circular importation in Python 2.7

For some reasons, I need this structure, here reduced for the explanation to 4 python files :

- main.py
- folder
  \- __init__.py
  \- loader.py
  \- folder1
     \- __init__.py
     \- class1.py
  \- folder2
     \- __init__.py
     \- class2.py

main.py :

import folder.loader as LD

LD.a.change_class2()
LD.b.change_class1()

loader.py :

from folder1.class1 import Class1
from folder2.class2 import Class2

a=Class1()
b=Class2()

class1.py :

import folder.loader as LD

class Class1():
    def __init__(self):
        self.pty1=0
    def change_class2(self):
        LD.b.pty2=2

class2.py :

import folder.loader as LD

class Class2():
    def __init__(self):
        self.pty2=0
    def change_class1(self):
        LD.a.pty1=6

The code executed is main.py. This script calls the file loader.py which creates an instance for Class1 and Class2. The instances have to communicate and modify each other, explaining the necessity (if I am not wrong) of the file loader.py.

Executing this code returns the error from class1.py :

    import folder.loader as LD
AttributeError: 'module' object has no attribute 'loader' 

I have no idea of what is going on here.

Surprisingly, when I remove the part as LD from the importation command line in the classes files, it works perfecly :

class1.py :

import folder.loader

class Class1():
    def __init__(self):
        self.pty1=0
    def change_class2(self):
        folder.loader.b.pty2=2

class2.py :

import folder.loader

class Class2():
    def __init__(self):
        self.pty2=0
    def change_class1(self):
        folder.loader.a.pty1=6

For this example, it's ok, but in the real program I am trying to make, based on this structure, I can't use the complete module path each time I need to communicate with another class instance.

Why am I getting this error ? What can I do to solve this ? Thank you in advance for your help.


EDIT : replacing import folder.loader as LD by from .. import loader as LD now returns another error, that I don't understand :

    from .. import loader as LD
ImportError: cannot import name loader
qcha
  • 523
  • 1
  • 5
  • 19
  • 1
    "I am encountering a problem using a circular importation" - okay, obvious first suggestion, don't use circular imports. You think that you "need this structure", but it's highly likely you can change things to not require circular imports. – user2357112 Mar 29 '17 at 21:45
  • 1
    possibly helpful: [How to avoid circular imports in Python?](http://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python) – chickity china chinese chicken Mar 29 '17 at 21:46

1 Answers1

0

I solved the problem simply by using Python 3, without code changes.

qcha
  • 523
  • 1
  • 5
  • 19