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

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

问题描述

这又是一个案例,我在圈子里跑来跑去,我即将疯狂。

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

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

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

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

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."

如何在Python 中处理循环依赖关系,并且最小化

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?

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


  • 好的选择:重构你的代码不要使用循环导入。

  • 错误选项:将您的一个 import 语句移到另一个范围。

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

但不,你不能预先解析文件。这不是Python的工作方式,如果你研究一下Python是如何工作的,那很明显是为什么。

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天全站免登陆