[Python] Avoiding circular imports in Python store management system

Discussão em 'Python' iniciado por Stack, Novembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    I'm building a store management system where different store components need to navigate between each other. I'm running into circular import issues and currently solving them by importing inside methods, but I feel this isn't the best approach. Here's a simplified version of my code:

    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)


    department_store.py

    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)


    section_store.py

    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)


    The stores form a hierarchy where:

    • BaseStore can navigate to DepartmentStore (e.g., Electronics, Clothing)
    • DepartmentStore can navigate to SectionStore (e.g., TVs within Electronics)
    • SectionStore can navigate back to its parent DepartmentStore

    Currently, I'm handling the circular imports by:

    • Using TYPE_CHECKING for type hints
    • Importing the required classes inside the methods

    While this works, I feel like there might be a better pattern or architecture that could avoid these circular imports altogether. Is there a more elegant way to structure this code?

    Some ideas I've considered:

    • Moving all store classes into a single file (feels wrong for maintainability)
    • Creating a separate store factory class (seems like overengineering)
    • Using dependency injection somehow
    • Creating an abstract navigation interface

    What's the pythonic way to handle this kind of store navigation pattern?

    Continue reading...

Compartilhe esta Página