Why is my python import not working?

It works:

from story.apps.document import core print core.submit() 

This does not work:

 from story import apps print apps.document.core.submit() 

"history" is a catalog. Inside it there is a directory called “apps”. Inside it there is a "document" directory. "core.py" is the file.

Each directory has __init__.py .

+4
source share
5 answers

In the __init__.py file, python interprets the directory as a package, but it does not necessarily tell python to import subpackages or other files from the directory (although it could be if you add the appropriate import statements).

With large package hierarchies, it is often preferable to require subpackages to be imported explicitly.

+7
source

When you execute story.apps.document import core , you tell the Python interpreter to match the story.apps.document description story.apps.document , import it, and then load the core variable from its namespace into your current one.

Because core is a file module that it has in its variables the namespaces defined in this file, for example, submit .


When you run from story import apps , you tell the Python interpreter to match the story description module, import it, and then load the apps variable from its namespace into your current one.

Since apps is a directory module, it has namespaces defined in its __init__.py and other modules in this directory in its variables. So apps knows about document , but knows nothing about the document core submodule.


FYI: The reason it sometimes confuses people is due to such things ...

It works well:

 # File1 import story.apps.document story.apps.document.core() 

Does not work:

 # File2 import story story.apps.document.core() # <-- Looks like the same function call, but is an Error 

For file1 Import works because the import operation tries to intelligently find things in the file system. The function call works because the document module has been imported and it is simply called story.apps.document .

For file2 calling a function does not work because there is nothing reasonable about the point operator, it just tries to access the attributes of the Python object - it knows nothing about file systems or modules.

+5
source

when you make history import from applications, you do not include all subpackages inside applications, for this you do something like

from story.apps.document import *

+1
source

This only works if story/__init__.py imports apps .

+1
source

In the second example, you import only the package. Python does not automatically import subpackages or modules. You must explicitly do this, as in the first example. Make dir(apps) and you will see that this is just an empty package.

0
source

Source: https://habr.com/ru/post/1345641/


All Articles