Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

import - Handle circular dependencies in Python modules?

this is a case again where I'm running around in circles and I'm about to go wild.

I wish Python would analyze all files at first, so that it would know all identifiers from the beginning (I think like Java does).

I have a "main.py" and a "gui.py". Every file contains a class, that makes use of the class in the other file. When I try to run "main.py", the interpreter imports "gui", then in "gui.py" it imports "main", then it processes the whole main module and says: "Tee-hee, there is no class with the given name in gui.py."

How can I handle circular dependencies in Python with minimum fuss?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I thought I'd expand this into an answer instead of a comment.

It's worth noting that circular imports are generally a sign of bad design: instead of demanding the language suit your design, why not change that design?

There are ways around this problem in python:

  • The good option: Refactor your code not to use circular imports.
  • The bad option: Move one of your import statements to a different scope.

But no, you can't pre-parse files. That's not the way Python works, and if you look into how Python works, it's pretty obvious why.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...