Search code examples
pythonpython-module

Mixing functions and subpackages in Python packages


Is there a way to mix subpackages and functions in my Python packages?

Currently, my layout is roughly like this:

lib/
   __init__.py
   Transform.py
   Statistic.py

where Transform.py and Statistic.py contain several functions each. To use them I do something like

from lib import Transform

Transform.fft(signal);

Now I would like to be able to have a function in a package inside Transform:

from lib.Transform import bins

Transform.bins.extent(signal);

Is that even possible? How would I have to define my packages to do that?


Solution

  • Solution #1: Try the following layout:

    lib/
      __init__.py
      Statistic.py
      Transform
        __init__.py
        bins.py
    

    In this case Transform.fft goes inside lib/Transform/__init__.py and Transform.bins.extent inside lib/Transform/bins.py

    Solution #2: If you wish to keep __init__.py short and clean, you can also create a separate Python-module (like fft.py) and import it in __init__.py as follows:

    from fft import *
    

    In which case you can also use:

    from lib.Transform import fft