Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - How to make a module act as package with __path__ variable?

I was trying to dig deep into python import mechanism and came across this in the Packages section of the documentation:

It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a __path__ attribute is considered a package.

It looks interesting but I could not find any example demonstrating this! So, how to actually implement it? In real world scenarios do you ever need such implementation?

question from:https://stackoverflow.com/questions/65950138/how-to-make-a-module-act-as-package-with-path-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Manually creating a "package" by setting __path__ would be a really weird thing to do, and I've never seen a use case for it. The import system core should handle it correctly, but code that expects "normal" packages is likely to break in all sorts of exotic ways. You probably shouldn't do this.

That said, what you're asking for would be as simple as putting

__path__ = ['whatever', 'list', 'of', 'directories', 'you', 'want']

in the module you want Python to treat as a package. Python will then treat the module as a package, and look for submodules in the directories specified in your artificial __path__.

For example, if you have the following directory structure:

.
├── contents
│   └── submodule.py
└── package.py

where package.py contains

import os

__path__ = [os.path.join(os.path.dirname(os.path.abspath(__file__)), 'contents')]

and contents/submodule.py contains

x = 3

then import package.submodule will treat package.py as a package and contents/submodule.py as the package.submodule submodule of the package package, and package.submodule.x will resolve to 3.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...