简体   繁体   English

如何仅导入模块的一部分并停止在Python中编译其他部分?

[英]How to import only one part of a module and stop compiling other parts in Python?

I have 2 files in my project- 我的项目中有2个文件-

**file1.py**
class A():
    # Some code...

class B():
    # Calling an API to get the data

Another file is- 另一个文件是-

**file2.py**
from file1 import A
# Some code....

The problem here is that I only want to import class A, but due to python default behavior it does compile the code written inside class B as well, which is calling an API unnecessary. 这里的问题是我只想导入类A,但是由于python的默认行为,它也确实编译了在类B内编写的代码,这不需要调用API。

How to fix it? 如何解决?

Just split out that code into separate modules, or refactor class B to not call an API on import. 只需将代码拆分为单独的模块,或重构类B以免在导入时调用API。

Partial imports are not supported out of the box in Python; 在Python中不支持部分导入。 the only option the import mechanism gives you is loading the whole file only . import机制给您的唯一选择是加载整个文件。

This means you'd have to do your own text file loading, then parse out the parts you want, then compile and execute those parts. 这意味着您必须自己加载文本文件,然后解析出所需的部分,然后编译并执行这些部分。 This is fraught with problems, because you'd have to detect any dependencies yourself to make an informed decision as to what can and can not be omitted. 这充满了问题,因为您必须自己检测任何依赖关系,才能就哪些可以省略和哪些不能省略作出明智的决定。

If you really want to go this path, you'll want to look at the ast module to produce a tree of the objects contained in a module file. 如果您真的想走这条路,则需要查看ast模块,以生成包含在模块文件中的对象树。 I'd use the line numbers on the objects to determine what parts of the original source file to compile (converting the tree back to bytecode is harder). 我将使用对象上的行号来确定要编译的原始源文件的哪些部分(将树转换回字节码比较困难)。

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

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