Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 568
Christian Abbott Avatar asked Apr 11 '15 16:04

Christian Abbott


2 Answers

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.

like image 70
daliusd Avatar answered Oct 17 '22 14:10

daliusd


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

Note that it requires pyflakes.

like image 22
Roland Smith Avatar answered Oct 17 '22 15:10

Roland Smith