简体   繁体   English

模块化python代码

[英]Modularizing python code

I have around 2000 lines of code in a python script. 我在python脚本中有大约2000行代码。 I decided to cleanup the code and moved all the helpers in a helpers.py file and all the configs and imports in a config.py file Here my main file: 我决定清理代码,并将所有帮助器移到helpers.py文件中,并将所有配置和导入移到config.py文件中,这里是我的主文件:

from config import *
from helpers import *
from modules import * 

And in my config file I've writted 在我的配置文件中

import threading as th

And then in modules I am extending a thread class 然后在模块中,我扩展了一个线程类

class A(th.Thread):
...

I get an error that th is not defined.And when I import config in my modules class, it works fine. 我收到未定义的错误,并且在我的模块类中导入配置时,它工作正常。 I don't have a clear picture on how imports work here. 我对此处的导入方式没有清楚的了解。 Also, is there any best practice to do it? 此外,是否有最佳做法?

Read import threading as th as th = __import__("threading") : it's an assignment first and foremost. th = __import__("threading")读取import threading as th :这是第一个也是最重要的任务。 Thus, you have to do the import in every file where you're using the variable. 因此,您必须在使用该变量的每个文件中进行导入。

PS: import * is best avoided. PS:最好不要import *

Python's from module import * isn't the same as require/include that you may see in other languages like PHP. Python的from module import *与在其他语言(例如PHP)中可能看到的require / include不同。

The star import works by executing/loading the module first, then merging the module's namespace to the current namespace. 星型导入的工作方式是先执行/加载模块,然后将模块的名称空间合并到当前名称空间。 This means that module have to import its own dependencies itself. 这意味着module必须自己导入自己的依赖项。 You can do that by adding from config import * in module , or better to do import threading as th in module as well. 您可以通过from config import *module添加来做到这一点,或者最好在module中也进行import threading as th

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM