Stuck at reusing code from parent package in Python

Question:

I have a bunch of scripts for static code analysis.

The get a directory as the command line argument, and they run on all files inside that directory.

Here’s the structure of my project:

__init__.py
run.py
message.py
globals.py
react
    __init__.py
    run.py
    check_imports.py
    analyze_states.py
next
    __init__.py
    check_routes.py
    analyze_images.py
git
   __init__.py
   check_size.py
   ensure_branch_name.py
   run.py => how can I call this and still access message.py?

Now, if I use top-level run.py as the orchestrator to call sub-modules inside sub-packages, everything works great and I can use import message from each sub-module.

But for git package, I want to call it directly. And I want to use functions defined inside message.py. I’m stuck at this point.

I saw Python import from parent package and tried from .. import message but it does not work.

Asked By: Big boy

||

Answers:

The way I did find out is for the git parent folder to be in your python path.
In general when I am developing I would add this lines in your git/run.py

import sys
sys.path.append('..')

Then you will be able to import message

When you finish with development and it is ready for pip install you need to make sure that message is an importable module in your setup.py for example.

Update

The ‘..’ will only work if you execute the git/run.py script or module from within the git repository as ‘..’ is a relative path.

If you want to execute run.py from anywhere you can do:

import os
import sys

parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir)

Just have in mind that __file__ will only exist if you execute run.py in batch mode not from an interactive shell or a notebook.

Answered By: dmontaner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.