Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: import the containing package

People also ask

How do I import a package in Python?

Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.

Can we import package inside function Python?

In Python, you can import the standard library, packages installed with pip, your own packages, and so on, with the import statement. This article describes the following contents. See the following article for the module search path.


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

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.


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.


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()