Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a path to sys.path in python and pylint

Tags:

python

pylint

So. I'm aware that this question seems to have been asked to death, but none of the answers seem to address what I want to do.

I have a library in another directory that I want to include in a set of other projects that I run. I don't want that library added every time I run python..

So, what I had been doing was this in my python code:

import sys
sys.path.append("/tmp/demo/src/my-lib")
import MyClass

and this worked fine. But, now that I've discovered and love pylint, it complains that

E:  7, 0: Unable to import 'MyClass' (import-error)
C:  7, 0: Import "import MyClass" should be placed at the top of the module (wrong-import-position)

I know I could just disable import-error and wrong-import-position with a directive (or just by putting it into .pylintrc...) But, I'd rather not. I'd like to know the "right" way of adding a path to sys.path that's not global to all my projects, just to the subset of projects that use that particular library.

Is this possible?

like image 548
bnsh Avatar asked Jun 24 '17 04:06

bnsh


People also ask

How do you add to a path in Python?

APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search. The following example shows how this can be done.

How do I permanently add to SYS path?

You can't “add a file to sys. path “. You always add its directory and then you can import the file.

Is Pythonpath same as SYS path?

PYTHONPATH is related to sys. path very closely. PYTHONPATH is an environment variable that you set before running the Python interpreter. PYTHONPATH , if it exists, should contain directories that should be searched for modules when using import .


1 Answers

You can do it using an "init hook" for pylint. See this answer: https://stackoverflow.com/a/3065082/4323

And this statement from pylint's bug tracker:

We will probably not going to support this automatically. But right now we do support manually additions to path, although in a more cumbersome way, through ``--init-hook="import sys; sys.path.append(...)"

like image 133
John Zwinck Avatar answered Sep 19 '22 15:09

John Zwinck