简体   繁体   English

没有“来自”的 Python 导入

[英]Python imports without "from"

I have a project with the following directory structure:我有一个具有以下目录结构的项目:

dir1目录1
--dir2 --dir2
----file1.py ----file1.py
----file2.py ----file2.py
--file3.py --file3.py

In file3, I call a function in file1.在file3中,我调用了file1中的一个函数。 In file1, it calls a function in file2, so it imports file2.在file1中,它调用了file2中的一个函数,所以它导入了file2。 Other files in dir2 are also imported by file1. dir2 中的其他文件也由file1 导入。

Currently, file1 causes a ModuleNotFound error on the line import file2 .目前, file1 在import file2行上导致 ModuleNotFound 错误。 This can be resolved by changing it to from dir2 import file2 , but the issue is I would need to go through all the files in dir2 and try to fix the imports.这可以通过将其更改为from dir2 import file2来解决,但问题是我需要检查 dir2 中的所有文件并尝试修复导入。

dir2 is a project found on Github and I would really not want to change all the imports every time I pull any changes. dir2 是在 Github 上找到的一个项目,我真的不想每次拉任何更改时都更改所有导入。 Is there a way to import file2 for use in file1, without having to change the imports?有没有办法导入 file2 以在 file1 中使用,而无需更改导入?

I am using Python 3.9.12.我正在使用 Python 3.9.12。

Python performs module resolution based on the sys.path variable. Python 基于sys.path变量执行模块解析。 You can append dir2 to this path so that any imports within it can be resolved:您可以将dir2附加到此路径,以便解析其中的任何导入:

file3.py文件3.py

import sys
sys.path.append("dir")

<other imports>

Alternatively, you can augment sys.path by using the PYTHONPATH environment variable:或者,您可以使用PYTHONPATH环境变量来扩充sys.path

$ PYTHONPATH=dir python3 file3.py

Keep in mind that path modifications are typically a code smell and should only be used when absolutely necessary.请记住,路径修改通常是代码异味,仅应在绝对必要时使用。 You can most likely resolve the root problem by having this "directory" (third party dependency) included in your project as a true pip installed dependency, then it will be "on path".您很可能通过将此“目录”(第三方依赖项)作为真正的 pip 安装依赖项包含在项目中来解决根本问题,然后它将“在路径上”。 Beyond that, you should only override third party code through your first party modules, not by adding files directly into their directories.除此之外,您应该只通过您的第一方模块覆盖第三方代码,而不是直接将文件添加到它们的目录中。

ie IE

from <dependency> import <class>

class App<Class>(<Class>):
    def overriden_method(self):
        return "my custom functionality"

References:参考:

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

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