Python: import the containing package

PythonModulePackagePython Import

Python Problem Overview


In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?

Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names...

Is there a pythonic way to do this?

Python Solutions


Solution 1 - Python

Also, starting in Python 2.5, relative imports are possible. e.g.:

from . import foo

Quoting from http://docs.python.org/tutorial/modules.html#intra-package-references:


Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use:

from . import echo
from .. import formats
from ..filters import equalizer

Solution 2 - Python

This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the __init__.py file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the __init__.py file that will import that function (when the package is imported) as well.

Solution 3 - Python

If the package is named testmod and your init file is therefore testmod/__init__.py and your module within the package is submod.py then from within submod.py file, you should just be able to say import testmod and use whatever you want that's defined in testmod.

Solution 4 - Python

I'm not totally sure what the situation is, but this may solve your "different name" problem:

import __init__ as top
top.some_function()

Or maybe?:

from __init__ import some_function
some_function()

Solution 5 - Python

In Django, the file manage.py has from django.core.management import execute_manager, but execute_manager is not a module. It is a function within the __init__.py module of the management directory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionguyView Question on Stackoverflow
Solution 1 - PythonBrian ClapperView Answer on Stackoverflow
Solution 2 - PythonmipadiView Answer on Stackoverflow
Solution 3 - PythonEli CourtwrightView Answer on Stackoverflow
Solution 4 - PythoncdlearyView Answer on Stackoverflow
Solution 5 - PythonmikemikeView Answer on Stackoverflow