Robert Basic's blog

Force Python version in Vim

by Robert Basic on January 12, 2017.

Vim can be compiled with Python support. Vim can be compiled with both Python 2 and Python 3 support.

At the same time.

But not really.

Vim can have both of them, but use only one at a time. If you start using one version, there is no way to switch to the other one.

The silly thing is that if you simply ask Vim which version does it support, the first one asked and supported is going to be the one loaded and used. Trying to use the other one from that point will result in an error.

if has('python')
elif has('python3')
endif

Guess which one is loaded? Python 2.

Try calling Python 3 and ka-boom!

:py3 print('hello')
E836: This Vim cannot execute :py3 after using :python

Switch the order around:

if has('python3')
elif has('python')
endif

And now? Yup, Python 3.

Why is this ridiculous? Because if you have a bunch of Vim plugins loaded, the first one that asks for a specific Python version wins! Reorder the plugins and suddenly a different Python version is loaded.

Gotta love the software development world.

Luckily, this can also be used to fix the problem itself.

How?

Force one of the Python versions from the top of your .vimrc file:

if has('python3')
endif

Now you can have a little bit of sanity and be sure what Python version is Vim going to use. Of course, doing this might break plugins written solely for Python 2, so do it at your own risk.

Happy hackin’!

Tags: python, vim, vimrc.
Categories: Development, Software.

Thanks for reading! If you require help on a PHP project of any kind, let's talk!

To get notified when I write a new blog post or make a new screencast, subscribe:

Recent posts