0

i have two modules Book Class and Author Class .The author class module imports the book class module as follows

from BookClass import Book
from PersonClass import Person

class Author(Person):

and the book class module also imports the author class module as follows

from AuthorClass import Author

class Book:

when i run any of the two modules it gives me an import error.I am not sure of how to fix this error. Thanks in advance.

Marim
  • 11
  • 3
  • You are trying to do cyclic imports which is the reason for the error. – shad0w_wa1k3r Aug 19 '17 at 09:55
  • this can help 'https://stackoverflow.com/questions/45634342/circular-imports-and-class-fields-in-python3' – Kallz Aug 19 '17 at 09:56
  • 1
    Possible duplicate of [Circular (or cyclic) imports in Python](https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python) – shad0w_wa1k3r Aug 19 '17 at 09:56
  • @Kallz i tried the solution mentioned in https://stackoverflow.com/questions/45634342/circular-imports-and-class-fields-in-python3' but it didn't work .I am not sure but i think this is not the same case as mine because he doesn't have two classes which are mutually dependent on each other as in my case. – Marim Aug 19 '17 at 10:53

1 Answers1

1

You are getting this error because your book class module says

from AuthorClass import Author

Remember that import is an executable statement. When the interpreter executes that statement, the first thing it does is import this code:

from BookClass import Book

but at that moment the class Book isn't defined yet, because the definition of Book comes after from AuthorClass import Author.

You have two classes with mutual references, and I take it you have complete control over the module structure. If I were in that position I would make the problem go away by putting both class definitions in the same module.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • Putting them in the same module worked fine.But i wanted to separate them in different modules as a sort of organization. – Marim Aug 19 '17 at 10:54
  • I realize that| and in principle it's a good approach. But in a dynamic language, it doesn't work well if you have two classes that refer to each other. – BoarGules Aug 19 '17 at 11:20