K-Doe
K-Doe

Reputation: 559

Import with Two Files and both need the import

I have two py files and have simplified my problem of just a few lines.

One:

from Two import PrintTwo

class PrintOne(object):
    print('HelloOne')

Two:

from One import PrintOne

class PrintTwo(object):

    print('HelloTwo')

This brings up this message: cannot import name 'PrintTwo' as expected.

But my problem is I need to use some functions of these classes in both files.

I cant find a solution for that, how is the correct workflow for a case like this?

Kind regards

Upvotes: 1

Views: 35

Answers (1)

Dominique Barton
Dominique Barton

Reputation: 918

This is called circular importing and they can work, if you set them up properly. However, I'd not recommend using circular imports and rather refactor the code.

It's hard to say what to change on the code, if I don't see it. When I experience circular imports then I try to avoid them by refactoring the code. Possible solutions are:

  • Move bits of the "shared" code into an own Python module (recommended)
  • Lazy import a module/component, means only import it when you use it (works but not really shiny)

I can't show you an example based on the code above, because you only circular import the modules but don't use them.

As mentioned before, a workaround is using imports only when you use them, for example:

class PrintOne:

    def some_magic_method(self):
        from Two import PrintTwo

Upvotes: 3

Related Questions