Вот упрощенная версия моего кода:
Код: Выделить всё
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .department_store import DepartmentStore
class BaseStore:
def navigate_to_department(self, dept_id: str) -> "DepartmentStore":
# Import inside method to avoid circular import
from .department_store import DepartmentStore
return DepartmentStore(dept_id, self.inventory_system)
Код: Выделить всё
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .section_store import SectionStore
class DepartmentStore:
def __init__(self, dept_id: str, inventory_system):
self.dept_id = dept_id
self.inventory_system = inventory_system
def navigate_to_section(self, section_id: str) -> "SectionStore":
# Import inside method to avoid circular import
from .section_store import SectionStore
return SectionStore(self.dept_id, section_id, self.inventory_system)
Код: Выделить всё
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .department_store import DepartmentStore
class SectionStore:
def __init__(self, dept_id: str, section_id: str, inventory_system):
self.dept_id = dept_id
self.section_id = section_id
self.inventory_system = inventory_system
def navigate_to_parent_department(self) -> "DepartmentStore":
# Import inside method to avoid circular import
from .department_store import DepartmentStore
return DepartmentStore(self.dept_id, self.inventory_system)
BaseStore может перейти к DepartmentStore (например, электроника, одежда)
DepartmentStore может перейти к DivisionStore (например, телевизоры в электронике)
SectionStore может вернуться к своему родительскому DepartmentStore
В настоящее время я обрабатываю циклический импорт следующим образом:
Использование TYPE_CHECKING для подсказок типов
Импорт необходимых классов внутри методов
Хотя это работает, я чувствую, что может быть лучший шаблон или архитектура, которой можно было бы избежать этот круговой импорт в целом. Есть ли более элегантный способ структурировать этот код?
Некоторые идеи, которые я рассмотрел:
Перемещение всех классов хранилища в один файл (неудобно с точки зрения удобства обслуживания)
Создание отдельного класса фабрики хранилища (похоже на чрезмерную разработку)
Каким-то образом использовать внедрение зависимостей
Создание абстрактного интерфейса навигации
Какой питонический способ обработки такого типа хранилища шаблон навигации?
Подробнее здесь: https://stackoverflow.com/questions/792 ... ent-system
Мобильная версия