导入在另一个模块中定义的模块 [英] Import module defined in another module

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

问题描述

我有以下设置.第一个文件(config.py)定义了一个路径,该路径告诉file1.py导入哪个模块.

I have the following setup. The first file (config.py) defines a path, that tells file1.py which module to import.

#file:config.py
moduleToBeImported="/here/is/some/path/file2.py"
import file1

然后在file1.py中,导入config.py中定义的模块

Then in file1.py, I import the module that is defined in config.py

#file:file1.py
import imp
foo = imp.load_source('module.name',moduleToBeImported)

是否可以将config.py中的moduleToBeImported变量传递给file1.py?

Is it possible to pass the variable moduleToBeImported from config.py to file1.py?

在当前设置中,我得到预期的错误:NameError:未定义名称'moduleToBeImported'

In the current setup I get expected error: NameError: name 'moduleToBeImported' is not defined

推荐答案

简短答案-

长回答-也许可以.而,您不应该.循环进口将导致进口周期.那就不好了.

Long Answer - Maybe, you can. And NO, you shouldn't. Circular imports would result in import cycles. And that is bad.

例如,假设您在file1.py中导入了config.py.一旦您运行file1.py并调用config.pyconfig.py中的代码就会像其他任何python文件一样运行.此时,您最终将尝试从file1.py导入file1.py.

For example, let's say you imported config.py in file1.py. As soon as you run file1.py and it calls up config.py, the code in config.py runs just like any other python file. At this point, you would end up trying to import file1.py from file1.py.

Python可能会或可能不会检测到此周期,然后才能破坏系统的破坏力.

Python may or may not detect this cycle before it breaks havoc on your system.

通常来说,循环导入是一种非常不好的编码习惯.

Generally speaking, circular imports are a very bad coding practice.

您可以做什么-您的config.py应该包含最少的可运行代码.而是将所有配置变量和设置以及常规实用程序方法保留在那里.简而言之,如果file1.py包含关键代码,则不应将其导入到config.py中.不过,您可以在file1.py中导入config.py.

What you can do instead - Your config.py should contain bare minimal runnable code. Instead keep all configuration variables and settings and general utility methods in there. In short, if file1.py contains critical code, it shouldn't be imported into config.py. You can import config.py in file1.py though.

在此处了解更多信息: Python循环导入?

More reading here: Python circular importing?

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

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