Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import from parent directory and keep flake8 happy

This import works fine, but feels dirty in a few ways. Mainly that it uses a specific number in the slice* to get the parent path, and that it annoys the flake8 linter.

import os
import sys
sys.path.append(os.path.dirname(__file__)[:-5])
from codeHelpers import completion_message

It's in a file system that looks a bit like this:

parent_folder
    __init__.py
    codeHelpers.py

    child_folder
        this_file.py

(child_folder is actually called week1, hence the 5 in the slice)

This question is extremely similar to Python import from parent directory, but in that case the discussion focused on whether or not it was good to run tests from the end point. In my case, I have a series of directories that have code that uses helpers that live in the parent.

Context: each directory is a set of weekly exercises, so I'd like to keep them as simple as possible.

Is there a cleaner, more pythonic way to do this import?

@cco solved the number problem, but it's still upsetting the linter.

like image 837
Ben Avatar asked Mar 16 '17 04:03

Ben


People also ask

Does flake8 sort imports?

Project description A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely that they are grouped and ordered correctly.

How do you use relative import in Python?

Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.

Does importing a Python file run it?

When you import a module in Python, all the code in it will be run, and all the variables in that module will be stuck on that module object.


Video Answer


2 Answers

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).

like image 75
Labrys Knossos Avatar answered Nov 14 '22 21:11

Labrys Knossos


You can import from a module a level up in a package by using ... In this_file.py:

from ..codeHelpers import completion_message

Had you wanted to go more levels up just keep adding dots...

While I'm here, just be aware that from ..codeHelpers is a relative import, and you should always use them when importing something in the same package. from codeHelpers is an absolute import, which are ambiguous in Python 2 (should it import from in the package or from the unfortunately named codeHelpers module you have installed on your system?), and in Python 3 actually forbidden as a way to import from within the same module (i.e. they are always absolute). You can read the ancient PEP 328 for an explanation of the difficulties.

like image 29
daphtdazz Avatar answered Nov 14 '22 23:11

daphtdazz