Cyclic import error

Problem

There are four lines, repeating over the entire project, that causes a cyclic import error.

These four lines don’t really affect the actual code, only the optional type annotations but they nonetheless prevent me from importing my modules. These lines are:

from anki.cards import Card
from anki.cards import CardId
from anki.notes import Note
from anki.notes import NoteId

I need to import anki.notes but in that notes.py file, the file notes.py is left again at line 10 to import anki.cards, which then goes deeper and deeper, from collection.py over latex.py over hooks.py to hooks_gen.py. There, it gets stuck, because this is the first time where instead of writing import anki.cards, we wrote from anki.cards import Card.

Meaning, in hooks_gen.py, Python wants to prematurely leave hooks_gen.py (before it’s completely imported) and goes back to cards.py and the cycle begins anew.

Solution

We need to do a project-wide search-and-replace and replace these faulty lines

from anki.cards import Card
from anki.cards import CardId
from anki.cards import Card, CardId
from anki.notes import Note
from anki.notes import NoteId
from anki.notes import Note, NoteId

with these lines

import anki.cards
import anki.notes

That will already solve the problem because the faulty parts are just the optional type annotations.

To fix those too, we’d have to replace the shorter Card with the longer cards.Card (same for notes.Note instead of just Note, and similarly, CardId and NoteId).

Importing anki.collection first might resolve it. Or you can put the imports in a if TYPE_CHECKING block. python - import from typing within TYPE_CHECKING block? - Stack Overflow

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.