[Python] A tool that allows intuitive relative import

Problem presentation

--Python cannot ** import from a higher directory ** or a distant directory ** --Python relative import is not intuitive --It is not a relative position specification from "the file". If the calling file (the first python file to be executed) changes, ** relative import references will shift ** --In Python, ** Difficult to structure directories when importing your own tools from multiple projects ** --Because it is difficult to import upper directories and sibling directories

Conclusion

Install relative path reference package

pip install relpath
from relpath import add_import_path
add_import_path("../")  #Here, specify the location of the tool you want to import by relative reference

from my_module import some_function

Detailed explanation (relative import)

If you use the relpath package, as in the example below, You can achieve intuitive relative import of modules.

from relpath import add_import_path
add_import_path("../")

from my_module import some_function

some_function()

Looking at the above example, it seems to work just as sys.path.append ("../ "). However, if the hierarchical structure of the project folder is complicated and one module is used from different locations, sys.path.append ("../ ") may not be able to handle it. Therefore, it is recommended to always use ʻadd_import_path of the relpath` package when you want to implement relative import.

Other uses

If you use the relpath package, it is not limited to import Intuitive relative path reference is possible.

For example, consider a project consisting of multiple python files, such as:

.
`-- project_folder
    |-- parts
    |   |-- data.txt
    |   `-- script_B.py
    `-- script_A.py

In script_A.py, use script_B.py as shown below.

# script_A.py

# load script_B.py
from parts.script_B import get_data

print(get_data())

In this case, as in the code example below, Attempts to read "./data.txt " relative to script_B.py will fail. (Note 1)

(Note 1) Strictly speaking, it can be read by specifying the relative path from script_A.py, If the caller is changed to another location, it will not work properly and maintenance will be poor. To avoid this, we recommend using the relpath package.

# script_B.py

def get_data():
    with open("./data.txt", "r") as f:  # -> FileNotFoundError: [Errno 2] No such file or directory: './data.txt'
        return f.read()

So, if you write the following using the relpath package, You will be able to read "./data.txt " relatively. (Note 2)

# script_B.py

from relpath import rel2abs

def get_data():
    with open(rel2abs("./data.txt"), "r") as f:  # -> NO ERROR!!
        return f.read()

(Note 2) The python spec for relative paths is not necessarily wrong. The python spec (relative path specification is always interpreted relative to the first caller, regardless of the location of the file it describes) Even if the location (file) where commands such as reading a file are written changes while developing a program The advantage is that there is no need to change the path specification method. The relpath package is just a way to give programmers another option besides the python spec, so It is recommended to consider the necessity of use depending on the situation.

reference

--PyPI link for the relpath package - https://pypi.org/project/relpath/

Recommended Posts

[Python] A tool that allows intuitive relative import
Run a Python file with relative import in PyCharm
MALSS, a tool that supports machine learning in Python
[Python] Creating a scraping tool Memo
A memo that allows you to change Pineapple's Python environment with pyenv
A tool for easily entering Python code
[Python] Create a LineBot that runs regularly
A typed world that begins with Python
I made a tool that makes decompression a little easier with CLI (Python3)
A program that plays rock-paper-scissors using Python
I created a password tool in Python.
[Python] A program that rounds the score
Create a plugin that allows you to search Sublime Text 3 tabs in Python
A memo that I wrote a quicksort in Python
[Python / Tkinter] A class that creates a scrollable Frame
A nice nimporter that connects nim and python
Create a page that loads infinitely with python
A program that removes duplicate statements in Python
Publish a Python module that calculates meteorological factors
"Python Kit" that calls a Python script from Swift
Python: Create a class that supports unpacked assignment
A Vim plugin that automatically formats Python styles
I tried running alembic, a Python migration tool
Python module import
Import python script
Summarize Python import
[Python] A program that counts the number of valleys
Try to make a command standby tool with python
Tool MALSS (application) that supports machine learning in Python
Dynamically import / reload modules that have changed in Python
A tool that makes a standalone jar an executable file
Specify upper directory / subdirectory with relative import of Python
A simple Python HTTP server that supports Range Requests
I made a VM that runs OpenCV for Python
Tool MALSS (basic) that supports machine learning in Python
Python that merges a lot of excel into one excel
Problems when creating a csv-json conversion tool with python
From a book that programmers can learn ... (Python): Pointer
What's in that variable (when running a Python script)
Created a Python library DateTimeRange that handles time ranges
In Python, create a decorator that dynamically accepts arguments Create a decorator
[Python] How to write a docstring that conforms to PEP8
A server that echoes data POSTed with flask / python
Make a CSV formatting tool with Python Pandas PyInstaller
A function that easily calculates a listwise removal tree (Python)
[Python] A convenient library that converts kanji to hiragana
A memo that I touched the Datastore with python
[Python] A program that compares the positions of kangaroos.
A Python program that converts ical data into text
I made a toolsver that spits out OS, Python, modules and tool versions to Markdown
[Python] Creating a GUI tool that automatically processes CSV of temperature rise data in Excel
A learning roadmap that allows you to develop and publish services from scratch with Python
Introducing "Sherlock", a CLI tool that allows you to search for user names across SNS
A Python script that allows you to check the status of the server from your browser
A memorandum (masOS) that import tkinter could not be done with python installed from pyenv