简体   繁体   English

我可以跨同一个 python 包的模块重用导入吗?

[英]Can I reuse imports across modules of the same python package?

I have a package named "test" with several modules:我有一个名为“test”的包,其中包含几个模块:

master/
|-- __init__.py
|-- app/
|-- auth/
|-- test/
|---- | __ init __.py
|---- | test_A.py
|---- | test_B.py
|---- | test_C.py

all test_X.py import the same core modules:所有 test_X.py 导入相同的核心模块:

import unittest
from unittest.mock import patch
import json
from flask_sqlalchemy import SQLAlchemy

from master.app.app import create_app
from master.app.models import setup_db, subject_student, Subject, Student
from master.app.functions import query_a_record

I wonder if there is a way to create a single file that imports all of the above modules and imports that file into each test file.我想知道是否有一种方法可以创建一个导入所有上述模块并将该文件导入每个测试文件的单个文件。 I am just trying to avoid code repetition.我只是想避免代码重复。

What I have tried:我尝试过的:

  • Included all the imports in the __ init __.py file that is inside the test package then imported init into each test在测试包内的 __ init __.py 文件中包含所有导入,然后将 init 导入到每个测试中
  • Created a config.py inside the package and then imported config into each module.在包内创建一个 config.py,然后将配置导入每个模块。

Of course, none of those have worked.当然,这些都没有奏效。 Any suggestion as to how to write those imports just once and reuse that piece of code in all my test modules?关于如何只编写一次这些导入并在我的所有测试模块中重用那段代码的任何建议? Or that is not even possible?或者这甚至不可能?

I suggest you delve a little bit in how Python defines and manages namespaces .我建议您深入研究 Python 如何定义和管理名称空间

As for your question, config.py or __init__.py definitely import the required modules, but their names are tied to that namespace, so when you access any of those names within your testX.py scripts, it raises NameError because you're in a different namespace and that name is not recognized;至于您的问题, config.py__init__.py肯定会导入所需的模块,但它们的名称与该名称空间相关联,因此当您在testX.py脚本中访问任何这些名称时,它会引发NameError因为您在一个不同的命名空间,该名称无法识别; you have to qualify it with the name of the module it belongs to.你必须用它所属的模块的名称来限定它。

A typical function call would be:一个典型的函数调用是:

config.unittest.mock.patch()

You can easily avoid this qualification by importing all of config namespace:您可以通过导入所有config命名空间轻松避免这种限定:

from config import * 

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

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