How to prevent VSCode from reordering python imports across statements?

Question:

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?

Asked By: lvella

||

Answers:

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:

  • Install the Python extension for VSCode if you haven’t already done so.
  • Install a Python code formatter that maintains the order of imports, such as isort or yapf. You can do this by running the command pip install isort or pip install yapf in your terminal.
  • In VSCode, open the settings by clicking on the gear icon in the bottom left corner and selecting "Settings".
  • Search for "Python › Formatting: Provider" in the search bar.
  • Select "Edit in settings.json" to edit the settings.json file.
  • Add the following line to the file, depending on which code formatter you installed:
  • For isort: "python.formatting.provider": "isort"
  • For yapf: "python.formatting.provider": "yapf"
  • Save the file and close the settings.
Answered By: Sachin Chaurasiya

I did this in my code after the other imports and it seems to work so I can save the code with formatting.

import gi
gi.require_version('Gtk', '3.0')

if True:
    from gi.repository import GLib
    from gi.repository import Gtk, Gdk
Answered By: Kjell Ericson