Search code examples
pythonnamespacespython-packaging

Create namespace | Extend name tree at file level


For example, in C++ we can write

namespace MilkyWay{
    namespace AlphaCentauri {
        int Planets = 4;
    }
    namespace SolarSys {
        int Planets = 8;
    }
}

And then use it as MilkyWay::SolarSys::Planets

Is there a way to write something like namespace in C++? Or in other words is there a possibility to extend name tree not only at the level of folder nesting but also at the level of a single file?

Or. Suppose we have the following structure:

sound/                          Top-level package
  __init__.py               Initialize the sound package
  formats/                  Subpackage for file format conversions
          __init__.py
          wavread.py
          wavwrite.py
          ...
  effects/                  Subpackage for sound effects
          __init__.py
          echo.py
          surround.py
          ...
  filters/                  Subpackage for filters
          __init__.py
          equalizer.py
          vocoder.py
          ...

I can do from sound.formats import wavread but why I can not do from sound import formats?


Solution

  • Ok, my question is similar to Importing packages in Python

    The deal is

    However, having found the package directory, it does not then scan that directory and automatically import all .py files.

    So, to get this work we need add to the __init__.py needed submodules (.py files), so that python will import it.

    For example file sound/formats/__init__.py must contain

    from . import wavread, wavwrite
    

    And now

    from sound import formats
    
    formats.wavread.do_smth()
    

    Will work fine

    Thanks to @deceze