Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent script dir from being added to sys.path in Python 3

Is there a way to prevent the script's directory from being added to sys.path in python3? I'm getting import conflicts due to the fact that imports are relative in python. A legacy project I'm working with has a file called logger.py in the root directory of the script which conflicts with the built-in logger.

The custom build system that I use ends up creating symlinks to all the files and dependencies and in production, at runtime we use the -E flag to ignore any system set PYTHONPATH and set the path to what we want. But running tests/scripts from PyCharm doesn't work because of this conflict.

like image 368
fo_x86 Avatar asked Feb 10 '19 22:02

fo_x86


People also ask

Is SYS path append bad?

Most of the time, appending to sys. path is a poor solution. It is better to take care of what your PYTHONPATH is set to : check that it contains your root directory (which contains your top-level packages) and nothing else (except site-packages which i).

Is SYS path append temporary?

Appending a value to sys. path only modifies it temporarily, i.e for that session only. Permanent modifications are done by changing PYTHONPATH and the default installation directory.

How does Sys path get set in Python?

sys. path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. When a module(a module is a python file) is imported within a Python file, the interpreter first searches for the specified module among its built-in modules.


1 Answers

At the top of your script, you can try doing something like:

import os
import sys

# the first element of sys.path is an empty string, meant to represent the current directory
sys.path.remove('')

then do your normal imports.

Beware, this will cause all relative imports from your current directory to fail, potentially causing more problems than your legacy logger.py

With regards to your second question, whether or not there's anything that can be done to prevent the directory from being added to sys.path in the first place, the short answer is no. From the Python 3 docs on "module search path" :

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.


I suppose you could set up a symlink from your current working directory to another directory, keep your actual script there, and point the symlink at it. Also from the above docs (emphasis mine):

On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed.

like image 162
wpercy Avatar answered Oct 06 '22 00:10

wpercy