Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come my python import doesn't work?

Tags:

python

This works:

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

This doesn't work:

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

"story" is a directory. Inside it, there is "apps" directory. Inside it, there is "document" directory. "core.py" is a file.

There is a __init__.py in every directory.

like image 990
TIMEX Avatar asked Mar 29 '11 01:03

TIMEX


People also ask

Why I cant import in Python?

This error generally occurs when a class cannot be imported due to one of the following reasons: The imported class is in a circular dependency. The imported class is unavailable or was not created. The imported class name is misspelled.

How do I add an import to Python?

The Python import statement imports code from one module into another program. You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist.

What is Python import error?

ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised. If a module does not exist.

How do import work in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


1 Answers

The __init__.py file tells python to interpret the directory as a package, but it does not necessarily tell python to import sub-packages or other files from the directory (although it may, if you add the appropriate import statements).

With large package hierarchies, it is often preferable to require sub-packages to be imported explicitly.

like image 105
senderle Avatar answered Sep 22 '22 05:09

senderle