#πŸ”’ Circular Imports needed for readability

13 messages Β· Page 1 of 1 (latest)

fathom sigil
#

I am working on a project and have run into an issue with circular imports
creation.py

from questions.survey_question import SurveyQuestion, QuestionType
from questions.text_question import TextQuestion

survey_question.py

from questions.text_question import TextQuestion

text_question.py

from questions.survey_question import SurveyQuestion, QuestionType

The reason for this design choice is that TextQuestion inherits SurveyQuestion
And in survey_question.py I have a helper function that takes a list of question entries from my database and turns them into the proper subclass of SurveyQuestion

async def from_db(row) -> SurveyQuestion:
    if row["type"] == QuestionType.TEXT:
        return await TextQuestion.load(row)

How can I avoid Circular Imports?
I looked at #1293650536834531428 but it did not seem to help

olive groveBOT
#

@fathom sigil

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

fathom sigil
#

Would putting the from_db function in its own file with this work?

from questions.text_question import TextQuestion
if TYPE_CHECKING:
    from questions.survey_question import SurveyQuestion
jagged wyvern
#

the usual thing is to use strings for your type hints

#

that works just as well, and doesn't require that you import anything

fathom sigil
jagged wyvern
#

async def from_db(row) -> "SurveyQuestion":

fathom sigil
#

Ah ok, good to know. But This would not solve my issue in this case because of my latest message, correct?

#

I seem to have solved it (or hidden the problem 😬 ) by moving the import into the function that uses it

async def from_db(row) -> SurveyQuestion:
    if row["type"] == QuestionType.TEXT:
        from questions.text_question import TextQuestion
        return await TextQuestion.load(row)

I almost gurentee something is bad about this

jagged wyvern
#

naw, you see that occasionally; I think I just saw an example of that in the official Django docs

young linden
#

Usually we try to move the base class sideways. Do you have plain hierarchy of classes? Can't TextQuestion be defined in questions/__init__.py ?

Is this just for type annotations, or for things which genuinely need to use some circular definition?

olive groveBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.