简体   繁体   中英

Adding a path to sys.path in python and 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?

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(...)"

This is an old post but after searching for a while I couldn't really find an easy solution for my problem so perhaps this workaround can also be useful for others. Recently I experienced a similar issue when using a python linter in Visual Studio Code: every time I saved my python file in VSC the linter would place the sys.import behind the import code and therefore my modules could not be loaded.

I know it can be solved by changing PYTHONPATH etc and by changing linter config files but in my case I'm unable to change all this because the module is part of another application.

As a workaround I solved the lint errors by doing:

import sys

if 1==1:
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
    import mylib

This stopped the linter to complain and the VSC formatter to rearrange my import rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM