Search code examples
pythonpython-3.xpython-module

Module/class visible in whole project - Python


So basically I need a class that will be visible in all sub directories of a project. The class is defined in the bar.py script and I need to instance an object in scripts where the <here> tag is placed.

The project structure look as follow and the program starts with the start_script.py.

base/
  start_script.py
  gui/
      __init__.py
      gui.py
      <here>
  vending/
      __init__.py
      vending.py
      <here>
  foo/
      __init__.py
      foo.py
      <here>
  bar/
      bar.py
      __init__.py

I already tried the relative import but it doesn't seems to work. Then I tried the dumbest solution to copy the required class everywhere I needed it, but I don't think it is a good practice to have copies of the same file all over the project.

The second solution that I tried is to copy the bar folder to the site-packages. It worked but I'm not sure if it is wise to copy a module that will be probably used only in this project to the site-packages.

Any suggestions?


Solution

  • (I edited my answer with the new content of the edited question)

    Your project needs a __init__.py file at the same level as start_script.py to use relative imports.

    Now you could add your class SpecialSnowflake in, for example, start_script.py and use it like this:

    # file base/gui/gui.py
    from ..start_script import SpecialSnowflake
    
    # file base/vending/vending.py
    from ..start_script import SpecialSnowflake
    
    # file base/foo/foo.py
    from ..start_script import SpecialSnowflake
    

    Does that work for you?