3

Here's a simple diagram that illustrates the problem

Description: there is a Pipeline entity that contains a Source entity, the Source is validated using the SourceValidator, and it in turn, in order to validate the source, must create a test pipeline, which can be created using the PipelineManager. Thus, there is a circular dependency of two packages on each other.

In a statically typed language I would create an interface on which the SourceValidator will depend, and in the pipeline package I would implement it and inject a specific instance into the SourceValidator using a Dependency Injection Container

But as I know this is not a pythonic way to use dependency injection containers, so could please someone help to understand what will be the pythonic way of dealing with this problem?

Anton Zelenin
  • 41
  • 1
  • 4
  • If there is already a Pipeline entity, doesn't that mean that there's already a PipelineManager that can help create the test pipeline? – thlik Dec 02 '20 at 14:05
  • Yes, of course, but when I try to import it inside the Source package it causes the circular import. pipeline module imports source package, source's init.py imports validator, validator imports manager, manager imports Pipeline class and Pipeline is not defined yet. – Anton Zelenin Dec 02 '20 at 14:15
  • Well, The Zen of Python (do `import this` on the CLI) reads `There should be one-- and preferably only one --obvious way to do it.` and your solution applies to any programming language. That's the "diamond problem" and what you suggest sounds like the right way to do it for me. You need a specific instance to inherit from and break the cycle. – thlik Dec 02 '20 at 14:22
  • ok, so say SourceValidator will depend on the abstract class, then we need some place outside of the source package where we need to create a specific instance and pass it to the SourceValidator, the only option I see now is to use dependency injection container but I read multiple discussions and everywhere people say it's not needed in Python because it might be done more simply. So the question is "is it ok to use DIC, if not, how to inject a specific instance another way?" – Anton Zelenin Dec 02 '20 at 15:25
  • 1
    I don't see any reason not to do it, here's an example https://medium.com/@shivama205/dependency-injection-python-cb2b5f336dce. I mean, you could try using namespaces and mock the instance but deep down it's the same solution. – thlik Dec 02 '20 at 15:43
  • 1
    have read this article, just wasn't sure if it's the best approach, thanks for replies :) – Anton Zelenin Dec 02 '20 at 15:53

0 Answers0