Python: import containing package

In the module inside the package, I have to use the function defined in __init__.py this package. how can i import a package inside a module that is inside a package so i can use this function?

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

Is there a pythonic way to do this?

+52
python module package python-import
Jan 12 '09 at 18:38
source share
5 answers

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

 from . import foo 

Quote 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 import form of the import from the import form. These explicit relative imports use leading points to indicate the current and parent packages involved in the relative import. For example, from the surrounding module, you can use:

 from . import echo from .. import formats from ..filters import equalizer 
+41
Jan 12 '09 at 19:52
source share
— -

This doesn’t exactly answer your question, but I suggest you move the function outside of the __init__.py file to another module inside this package. Then you can easily import this function into your other module. If you want, you can have an import statement in the __init__.py file that will import this function (when importing the package).

+20
Jan 12 '09 at 18:40
source share

If the package is named testmod , so your initialization file is testmod/__init__.py , and your module is in the submod.py package, and then from the submod.py file, you should just say import testmod and use it regardless of what you want, defined in testmod.

+5
Jan 12 '09 at 19:13
source share

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

+1
Apr 02 '09 at 2:30
source share

I'm not quite sure what it is, but it can solve your “different name” problem:

 import __init__ as top top.some_function() 

Or maybe ?:

 from __init__ import some_function some_function() 
0
Jan 12 '09 at 19:26
source share



All Articles