pythonvisual-studio-codecode-formatting

How to prevent VSCode from reordering python imports across statements?


This is the correct way to import Gtk3 into python:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject

When I save such code in VSCode with "editor.formatOnSave": true, it gets reordered to:

from gi.repository import Gtk, Gdk
import gi
gi.require_version('Gtk', '3.0')

which makes Gtk to be loaded before I have the chance to specify the version I am using, which at very least leads to the following warning being displayed:

PyGIWarning: Gtk was imported without specifying a version first. Use gi.require_version('Gtk', '4.0') before import to ensure that the right version gets loaded.

or worse, get me an exception like:

ValueError: Namespace Gtk is already loaded with version 4.0

Now, I like VSCode code formatting, but I don't want it to reorder my imports, specially not across statements (being that imports in python have side effects). How to properly use VSCode's Python code formatter with Gtk?


Solution

  • To prevent VSCode from reordering Python imports across statements, you can configure the editor to use a specific Python code formatter that maintains the order of the imports as they are in the original code. Here's how you can do it: