Vim plugin for automatically generating Python import statements (without using Rope)

5.7k views Asked by At

I've seen similar questions asked before here and here, however they are 4 years old and did not yield answers that matched my requirements.

If I type Python code into Vim, for example:

os.path.join('my', 'path')
resp = requests.get('http://example.com')
HttpResponse('success')

Assuming that I had the third-party modules 'requests' and 'django' in my site-packages folder, is there any Vim plugin -- which does not use the Rope library -- that could automatically add the relevant import statements to the Python file (both for built-in & third-party modules, using either import or from as needed), like this:

import os
import requests
from django.http import HttpResponse

While I would traditionally use the venerable Rope package, I have been replacing Rope functions with modern alternatives to avoid the overhead of the .ropeproject folder. However, I haven't found a Vim alternative yet for auto-import.

3

There are 3 answers

5
daliusd On BEST ANSWER

I am using python-imports.vim (https://github.com/mgedmin/python-imports.vim). Combine that with gutentags plugin and it is almost perfect. Perfect solution would create all imports and magically guess correct modules in case of name collision but I doubt that this is possible.

Update 2022-05-14: Another way is to use Ale (https://github.com/dense-analysis/ale) with pyright (https://github.com/microsoft/pyright) and :ALEImport command.

3
Roland Smith On

Have a look at vimpy. From its description it does what you are looking for.

Note that it requires pyflakes.

0
LondonRob On

Very late to the party but since this question exists, I might as well post a new answer.

I use coc-python for everything of this nature.

It just works like magic:

enter image description here

The only caveat is that you have to press Ctrl-y to accept the Auto-import suggestion.

Make sure you haven't got Ctrl-y mapped to anything else in insert mode (a common plugin called Emmet remaps this combination, for example.)