[Python] What to do when PEP8 is violated in the process of importing from the directory added to sys.path

The version of Python I'm using is 3.6.

If you find any mistakes, I would be grateful if you could point them out in the comments.

Violation of PEP8

Suppose you want to load your own modules under `lib``` from` scripts / execute.py``` with such a directory structure.

.
├──scripts
│   └── execute.py
└──lib
    └── my_module.py

Initially, I tried to deal with it by writing execute.py as follows and adding a file to `` `sys.path```.

import pandas as pd
import sys
sys.path.append('../lib')
import my_module

# (The following is omitted)

However, this is the Python coding convention PEP8 (Japanese translation io / ja / latest / #)) is violated, so if you are using flake8 etc., the following Tsukkomi will be entered.

E402 module level import not at top of file

Let's quote corresponding part of Japanese translation.

The import statement should always be placed at the beginning of the file, immediately after the module comment or docstring, and before the module's global variable or constant definition.

Resolved by setting the environment variable PYTHONPATH

Just I had a question on Stackoverflow to the same effect.

Several methods were answered in this, and adding a directory to the environment variable `` `PYTHONPATH``` seemed to be the essential solution. (The following link was introduced)

(Although the following methods were also introduced, honestly, it looks like a cunning hack to me.)

Also, the Japanese question site teratail had answers to similar questions. The answer is from Sphinx committer Shimizukawa, so it seems to be highly credible.

Adjusting sys.path in a script is not recommended. If the directory where you want to use the library is fixed in various places and you want to import that library, there is a way to set the environment variable PYTHONPATH.

So I added the `` `libdirectory to PYTHONPATH and dealt with it. If you use it every time, write it in bash_profile```.

export PYTHONPATH="${PYTHONPATH}:/full path of lib directory/lib"

This allowed us to remove the `` `sys.pathrelated description fromexecute.py```.

import pandas as pd

import my_module

# (The following is omitted)

About the environment variable PYTHONPATH

It's not the main subject, but I was curious about what would happen if the library name and my own module name were batting.

In such cases, read the official documentation. There is the following description in the official Python tutorial.

When importing a module named spam, the interpreter first looks for a built-in module with that name. If not found, look for a file named spam.py in the list of directories in sys.path. sys.path is initialized to the following location:

  • The directory containing the entered script (or the current directory if no file is specified).

Apparently, the one in PYTHONPATH has priority. Even when I actually tried it, it behaved like that.

Recommended Posts

[Python] What to do when PEP8 is violated in the process of importing from the directory added to sys.path
What to do when the value type is ambiguous in Python?
What to do if the progress bar is not displayed in tqdm of python
What to do when the warning "The environment is in consistent ..." appears in the Anaconda environment
What to do if you get `locale.Error: unsupported locale setting` when getting the day of the week from a date in Python
What to do when [Errno 2] No such file or directory appears in Python
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
What to do when is not in the sudoers file.This incident will be reported.
What to do when only the window is displayed and nothing is displayed in pygame Note
What to do if you get an error when importing matplotlib in Python (Mac)
What to do if Python does not switch from the System version in pyenv
What to do when "SSL: CERTIFICATE_VERIFY_FAILED _ssl.c: 1056" appears in Python
What beginners learned from the basics of variables in python
What to do if "Unnamed: 0" is added in to_csv-> read_csv in pandas
What to do when ModuleNotFoundError: No module named'XXX' occurs in Python
Write a script in Shell and Python to notify you in Slack when the process is finished
What to do when a part of the background image becomes transparent when the transparent image is combined with Pillow
NameError: global name'dot_parser' is not defined and what to do when it comes up in python
What is "mahjong" in the Python library? ??
What to do if there is a decimal in python json .dumps
[Python] What to do when an error related to SSL authentication is returned
What kind of book is the best-selling "Python Crash Course" in the world?
[Introduction to Python] What is the method of repeating with the continue statement?
What is the fastest way to create a reverse dictionary in python?
What to do when a warning message is displayed in pip list
What to do when "Something is already running at port 8000" is displayed when the develop command of Gatsby is executed.
How to write what to do when an application is first displayed in Qt for Python with Designer
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
[Python] When the priority is the same in Priority Queue, it can be acquired in the order in which it was added to the queue.
Example of what to do when the sample script does not work (OpenCV-Python)
What is wheezy in the Docker Python image?
What to do when a warning appears around Python integration in Neovim's CheckHealth
What to do if you get the error RuntimeError: Python is not installed as a framework when trying to use matplitlib and pylab in Python 3.3
About the handling of ZIP files including Japanese files when upgrading from Python2 to Python3
What to do when PermissionError of tempfile.mkstemp occurs
What to do if abort is displayed when inputting camera video in OpenCV
What I did when updating from Python 2.6 to 2.7
What to do when the graph does not appear in jupyter (ipython) notebook
What to do to get google spreadsheet in python
What to do if (base) is displayed at the beginning of the Mac terminal
How to get a list of files in the same directory with python
[Python] Type Error:'WebElement' object is not iterable What to do when an error occurs
[Python] What to do when No module named'pyproj.datadir' appears when Exe is done with PyInstaller
What to do if the print command itself causes an error in Maya python
What to do if Python IntelliSense is not displayed in VS Code on Windows
How to check in Python if one of the elements of a list is in another list
What to do when Python starts up in Anaconda does not come out unexpectedly
[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?
What to do if you can't hit the arrow keys in the Python interactive console
What I do when imitating embedded go in python
The wall of changing the Django service from Python 2.7 to Python 3
[Go 1.13] What to do when unexpected directory layout: appears
[openpyxl] What to do when IllegalCharacterError appears in pandas.DataFrame.to_excel
curl: (60) What to do when Issuer certificate is invalid.
How to get the number of digits in Python
How to know the current directory in Python in Blender
Find the part that is 575 from Wikipedia in Python
What to do when "cannot import name xxx" [Python]
I want to do something in Python when I finish
What to do when you can't bind CaboCha to Python
Make a note of what you want to do in the future with Raspberry Pi