将模块转换为包时出错 [英] Error converting module to a package

查看:69
本文介绍了将模块转换为包时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多简单辅助函数的模块,但它变得越来越大且维护起来很繁琐.我想把它分解成一个简单的包.我的包目录在 PYTHONPATH 上定义,如下所示:

I have a module with many simple helper functions, but it is getting large and tedious to maintain. I'd like to break it into a simple package. My package directory is defined on PYTHONPATH, and looks like this:

test
|--__init__.py          <---this is empty
|--a.py
|--b.py

这是以通常的方式导入(导入测试),但经过检查(目录(测试)),库不包含模块 a 或 b,仅包含一些顶级属性.我可以使用提示出了什么问题.谢谢!

This is imported in the usual way (import test) but upon inspection (dir(test)) the library does not contain the modules a or b, just some top level attributes. I could use a hint what is going wrong. thanks!

下面的解决方案: init 文件现在会自动加载我每次都想访问的模块.这尊重 Python 3.4 固有的绝对路径假设.

Solution from below: the init file now auto-loads modules that I want access to every time. This respects the absolute path assumptions inherent to Python 3.4.

from .a import a
from .b import b

跟进:我的意图是将每个辅助脚本作为自己的模块,从而产生许多易于查找和维护的小模块.这是惯用语吗?低效?我得到了 init 文件的维护含义.有什么经验或最佳实践可以分享?谢谢.

Follow-Up: My intent was to have each helper script as its own module, leading to perhaps many small modules that are easy to find and maintain. Is this idiomatic? inefficient? I get the maintenance implications to the init file. Any experience or best practices to share? thanks.

推荐答案

您还应该从包中import ab 以便 dir代码> 列出它们.如果要在导入包时自动导入包中的模块,请在__init__.py中指定,在__init__.py中添加要导入的模块的import语句

You should also import a and b from the package in order for dir to list them. If you want to auto import modules in a package when importing a package, specify in __init__.py by adding import statements of the modules you want to import in __init__.py

test           # package directory
├── module1.py
├── module2.py
├── __init__.py

要在每次导入包时导入 module1,__init__.py 必须包含以下内容.

To import module1 whenever you import the package, you __init__.py must contain the following.

import module1

您可以使用 from test import module2

编辑:

只要不同的模块服务于不同的目的,最好将所有相关的帮助程序保留在自己的模块中.导入包时默认要导入的所有模块都应在 __init__.py 文件中指定.其他的可以在需要时导入.即使您多次导入模块,它们也只初始化一次,如此处所述,也不应该有任何性能影响.

As long as different modules serve different purposes, its better to keep all the related helpers in their own module. All the modules that you want to import by default when your package is imported should be specified in the __init__.py file. Others can be imported whenever necessary. There shouldn't be any performance implications even if you import a module multiple times they are initialized only once as found here.

这篇关于将模块转换为包时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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