Search code examples
pythonpython-importflake8

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.


Solution

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