同一个模块被导入到不同的文件中 [英] Same module is being imported in different files

查看:15
本文介绍了同一个模块被导入到不同的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做是否不好:

在 first.py 中:

In first.py:

import second
import mymodule

在 second.py 中:

In second.py:

import mymodule

mymodule 正在两个文件中导入,而 first.py 导入 second.py.是否可以以某种方式导入 mymodule 一次?这没什么大不了的,只是不优雅,也不是 Pythonic IMO.

mymodule is being imported in both files and first.py imports second.py. Is it possible to somehow import the mymodule just once? It's not a big deal, it's just not elegant nor Pythonic IMO.

推荐答案

mymodule 只运行一次;导入它的每个模块共享相同的副本.没关系.如果您有任何循环导入(A 导入 B 导入 A,或 A 导入 B 导入 C ... 导入 A),请小心,因为这些会导致微妙的初始化顺序问题并使您混乱.

mymodule is only run once; every module that imports it shares the same copy. It's fine. Just be careful if you have any cyclic imports (A imports B imports A, or A imports B imports C ... imports A), because those can cause subtle initialization order problems and mess you up.

这篇关于同一个模块被导入到不同的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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