pythonpython-3.xpython-importcircular-dependencycyclic-reference

Python problem with imports from file in the same folder


i'm having a problem with imports: i have this folder structure:

Q2AInterface
    __init__.py
    Q2A.py
    Question.py
    Like.py
main.py

And to make it short the content are something like this:

Q2A.py:

from . import Question
from . import Like
class Q2A:
    pass

Question.py:

from . import Q2A
from . import Like

class Question:
    pass

Like.py:

from . import Question
class Like:
    question = Question.Question()

main.py:

#!/usr/bin/python3
from Q2AInterface import Q2A,Like,Question

Problem is that in Likes.py it gives me error when i use the Question class, the error is:

module 'Q2AInterface.Question' has no attribute 'Question'

I really have no idea how to fix this, i've tried writing the imports in every way i could think of, i tried:

import Question, import Question.Question, from .Question import Question, from . import Question.

i really have no idea what to do, tried reading some questions online too, but no matter what i try, init, or different imports, it just won't work...


Solution

  • you've landed in a python circular importing problem !

    basically in Question.py remove from . import Like, OR else, if you need it, put it after the class, like so.

    from . import Q2A
    
    class Question:
        pass
    
    from . import Like