Error converting module to a package

﹥>﹥吖頭↗ 提交于 2021-01-29 02:04:15

问题


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

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!

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

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.


回答1:


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

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

import module1

You can import a module from the test package with from test import module2

Edit:

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.




回答2:


I think the simplest answer is to import the modules you want like this:

import test.a
import test.b as b  # variant if you don't want the package name

Then you can call functions in the modules:

test.a.foo()
b.bar()


来源:https://stackoverflow.com/questions/36677288/error-converting-module-to-a-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!