#🔒 Circular import

6 messages · Page 1 of 1 (latest)

tawny hare
#

Hi guys, I'm dealing with a circular import caused by explicit typeclass registrations. I'm a bit confused what to do next.

I'm using github.com/dry-python/classes which is somewhat similar to functools.singledispatch.

So, I have to_dict, I'll dump only a part of the code to put into the context of ```py

Copyright (c) 2025 Osyah

SPDX-License-Identifier: MIT

from future import annotations

all: typing.Sequence[str] = ("to_dict",)

import typing

from classes import typeclass

from pletyvo.protocol.dapp.event import (
AuthHeader,
EventInput,
Event,
...
)

if typing.TYPE_CHECKING:
from typing import Any

@typeclass
def to_dict(instance) -> dict[str, Any]: ...

@to_dict.instance(AuthHeader)
def _to_dict_dapp_auth_header(instance: AuthHeader) -> dict[str, Any]:
from base64 import b64encode
return {
"sch": instance.sch,
"pub": b64encode(instance.pub).decode(),
"sig": b64encode(instance.sig).decode(),
}

@to_dict.instance(EventInput)
def _to_dict_dapp_event_input(instance: EventInput) -> dict[str, Any]:
return {
"body": str(instance.body),
"auth": to_dict(instance.auth),
}

@to_dict.instance(Event)
def _to_dict_dapp_event(instance: Event) -> dict[str, Any]:
return {
"id": str(instance.id),
"body": str(instance.body),
"auth": to_dict(instance.auth),
}

...


So, the problem I'm facing is that `classes.typeclass` requires passing the actual class object (e.g. `@to_dict.instance(AuthHeader))`, which forces me to import everything eagerly. One of those modules (e.g. `pletyvo.protocol.dapp.event`) ends up importing the serialiser  (`to_dict`) that registers it - and boom, circular import. Tricks like `TYPE_CHECKING` or deferring inside functions don't help because as i said registration happens at import time.

Anyone dealt with this?
pale violetBOT
#

@tawny hare

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.

stone vessel
#

Try putting the serializer in a different module.

odd stream
#
from __future__ import annotations
import typing
from classes import typeclass

if typing.TYPE_CHECKING:
    from typing import Any

__all__ = ("to_dict",)

@typeclass
def to_dict(instance) -> dict[str, Any]:
    """Converts an instance to a dictionary."""
    raise NotImplementedError(f"No to_dict implementation for type {type(instance)}")
pale violetBOT
#
Python help channel closed for inactivity

This help channel has been closed. 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.