处理 Python 模块中的循环依赖? [英] Handle circular dependencies in Python modules?

查看:23
本文介绍了处理 Python 模块中的循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这又是一个案例,我在圈子里跑来跑去,我要发疯了.

我希望 Python 首先分析所有文件,以便它从一开始就知道所有标识符(我认为就像 Java 一样).

我有一个main.py"和一个gui.py".每个文件都包含一个类,它使用另一个文件中的类.当我尝试运行main.py"时,解释器导入gui",然后在gui.py"中导入main",然后处理整个主模块并说:Tee-hee,没有类使用 gui.py 中的给定名称."

如何在 Python 中轻松处理循环依赖?

解决方案

我想我会将其扩展为答案而不是评论.

值得注意的是循环导入通常是糟糕设计的标志:与其要求语言适合您的设计,为什么不改变该设计?

在python中有解决这个问题的方法::>

  • 不错的选择:重构您的代码,不要使用循环导入.
  • 糟糕的选择:将您的 import 语句之一移动到不同的范围.

但是不,您不能预解析文件.这不是 Python 的工作方式,如果您研究一下 Python 的工作方式,原因就很明显了.

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?

解决方案

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.

这篇关于处理 Python 模块中的循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆