Question

I'm restructuring a python project that evolved from a small set of scripts in something bigger. I didn't think about a proper package structure before so all the scripts live in package root dir.

I'm trying to give the project a the proper "package" structure like this:

packagename/
    docs/
    packagename/
        __init__.py
        module_data.py
        module_corrections.py
        module_plot.py
        subpackage1/
        subpackage2/
    README.md

I want to support importing the package as:

from packagename import *

The effect of the previous import should be loading a few submodules or subpackages, but also some class and function that I would like to provide without prepending the module name.

Using __all__ in __init__.py I can only load submodules or subpackages.

How can I load, for example a Data() class from module_data and a function dplot from module module_plot?

Furthermore, how can I import module_data with another short name (e.g. mda)?

EDIT

Short Answer

All the names I want to provide must be imported or defined in __init__.py and added as string to the list __all__.

Thanks to @FMc for providing an example and insight.

Was it helpful?

Solution

Here's an example -- but, as a general rule, you shouldn't use wildcard imports (only under narrowly defined circumstances, and only if you define __all__).

# Directory structure.
.
├── foopack/
│   ├── __init__.py
│   ├── data.py
│   └── plot.py
└── run.py

# foopack/data.py
class Data(object):
    def blah(self):
        print self.x

# foopack/plot.py
def dplot():
    print 'dplot()'

# foopack/__init__.py
# Here we use relative imports and define __all__.
from .data import Data
from .plot import dplot    
__all__ = 'Data dplot'.split()

# A demo script: demo.py
from foopack import *

d = Data()
d.x = 32
d.blah()
dplot()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top