#🔒 Resolving Circular Dependency

11 messages · Page 1 of 1 (latest)

visual quest
#

Imagine you have a basic tensor class with softmax. Softmax is a random example here.

    from .nn import Softmax

    class Tensor(data):
        def __init__():
            self.data = data
        
        def softmax():
            return Softmax()

and you have this Softmax implementation in nn.softmax.py

    from .tensor import Tensor

    def Softmax(data):
        # do fancy math
        result = ...
        return Tensor(result)

Now we can do:

# import Tensor, Softmax

X = tensor(...)
X.softmax()
Softmax(X)

the current design is flawed though because we have a circular dependency: Tensor::softmax() uses Softmax() which uses Tensor which uses ....

How can I solve this?

Edit: Without using TYPE_CHECKING for type hints and moving the import Tensor inside of Softmax(). I want to avoid import inside functions.

unique jasperBOT
#

@visual quest

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.

visual quest
#

ah my actual issue is solved simply by using from __future__ import annotations

#

ah shoudl read correctly, my error is only regarding the type. everything makes sense now.

#

.cloe

lone robinBOT
#
Did you mean:
visual quest
#

.close

lone robinBOT
#
Did you mean:
visual quest
#

!close

unique jasperBOT
#
Python help channel closed with !close

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.