Display my project
's directory structure:
tree project
project
├── config.py
├── __init__.py
└── project.py
Content in project.py:
from . import config
def main():
pass
if __name__ == '__main__':
main()
Content in __init__.py
:
__all__ = ['project','config']
from project import *
from . import config
config.py
is blank for simplicity.
To load the module:
cd project
import project
It encounter the error info: Parent module '' not loaded, cannot perform relative import
Why can't import project
? I found that if project.py
renamed as myproject.py
, keep any other thing the same as before, import project
can work.
Does not the package project
share same name with module project.py
?
Why same names matter?
If you try to look at __package__
from project.py
, you will see that it changes from nothing when you import project
inside the project/
folder, and when you import project
just outside the folder. This is because, when you are inside the folder, you are importing the module project
(ie the project.py
file), and from outside the project/
folder you are importing the project
package (ie the you are running the __init__.py
file).
When writing from. import x
from. import x
, you expect to import x
from inside the current package, but there is no package context, therefore it cannot import.
According to this answer: https://stackoverflow.com/a/35710527/4393278
What does
__all__
do?
It declares the semantically "public" names from a module. If there is a name in all , users are expected to use it, and they can have the expectation that it will not change.
` all = ['foo', 'Bar'] means that when you import * from the module, only those names in the all are imported.
So you don't need to define __all__
if you want to import anything inside project.py
file. Also I think you should import a file is not by their path. So, inside your __init__
file, it should be like this.
from .project import *
from .config import *
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.