First since you haven't been specific about which lint error you are getting, I am going to assume it's because you have an import after your sys.path.append
.
The cleanest way to do it is with relative or absolute imports.
Using absolute imports:
from parent_path.codeHelpers import completion_message
Using relative imports:
from ..codeHelpers import completion_message
For the simple example listed in the original question this should be all that's required. It's simple, it's pythonic, it's reliable, and it fixes the lint issue.
You may find yourself in a situation where the above does not work for you and sys.path
manipulation is still required. A drawback is that your IDE will likely not be able to resolve imports to modules from the new path causing issues such as automatic code completion not working and flagging the imports as errors, even though the code will run properly.
If you find you still need to use sys.path
and want to avoid lint errors for this type of situation create a new module and do the sys.path
manipulation in it instead. Then make sure that you import your new module before any modules that require the modified sys.path
.
For example:
local_imports.py
"""Add a path to sys.path for imports."""
import os
import sys
# Get the current directory
current_path = os.path.dirname(__file__)
# Get the parent directory
parent_path = os.path.dirname(current_path)
# Add the parent directory to sys.path
sys.path.append(parent_path)
Then in the target file:
import local_imports # now using modified sys.path
from codeHelpers import completion_message
The drawback to this is it requires you to include local_imports.py
in each child_folder
and if the folder structure changes, you would have to modify each one local_imports
file.
Where this pattern is really useful is when you need to include external libraries in your package (for example in a libs
folder) without requiring the user to install the libs themselves.
If you are using this pattern for a libs
folder, you may want to make sure your included libraries are preferred over the installed libraries.
To do so, change
sys.path.append(custom_path)
to
sys.path.insert(1, custom_path)
This will make your custom path the second place the python interpreter will check (the first will still be ''
which is the local directory).