[Python] How to avoid circular imports when interfacing between a dataclass and database api

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a data factory class that gets athlete profile information in json format from an external API, and a public interfacing driver class that allows you to specify what years you want to get athlete data for, and interfaces with the database API to see if the athlete information returned doesn't already exist in our local database and whether athletes have had their profile information changed. The dataclasses look something like this:

    from database_api import upsert_country


    @dataclass
    class Country:
    id: int
    name: str
    abbreviation: str

    @classmethod
    def upsert(cls, **kwargs):
    upsert_country(cls(**kwargs))


    @dataclass
    class Athlete:
    id: int
    first_name: str
    last_name: str
    country_id: Optional[int]
    country: InitVar[Optional[Country]]

    def __post_init__(self, country):
    if country:
    Country.upsert(
    id=country['id'],
    name=country['name'],
    abbreviation=country['abbreviation']
    )
    self.country_id = country['id']


    Database API class:

    from models import Athlete, Country

    def get_athletes() -> list[Athlete]:
    query = ...
    res = select_many(query, row_factory=class_row(Athlete))
    return res

    def get_countries() -> list[Country]:
    query = ...
    res = select_many(query, row_factory=class_row(Country))
    return res

    def upsert_country(country: Country) -> None:
    query = ...
    insert_one(query, asdict(country))


    The issue I'm running into is that the Athlete has many attributes like Country, where I just need to upsert it to the database if it's new or its information has changed and only need its id as country_id for the Athlete to compare it against what I have in the database. But if I upsert from the dataclass, I have to import the upsert method from the database api module. And in the database api, I'm importing the dataclasses for type checking and as the row factory for queries for validation and comparison afterwards. How should I deal with this circular import?

    Continue reading...

Compartilhe esta Página