Skip to content

File formatter messes up imports if path dependent imports are used #298

@Pandafishie

Description

@Pandafishie

Diagnostic Data

  • Python version (& distribution if applicable, e.g., Anaconda): Python 3.13.1 @ conda 23.11.0
  • Type of virtual environment used (e.g., conda, venv, virtualenv, etc.): conda
  • Operating system (and version): Windows 11 Home ; OS build 26100.2605
  • Version of tool extension you are using:
    2024.0.0

Behaviour

Expected Behavior

Formatter does not move import order & lines past none-empty lines to prevent import issues

Actual Behavior

The formatter moves import lines to the very top of the file, regardless of any code in between. This can be fatal when importing relative packages from local paths using

sys.path.append(). As a result, imports imported from local added paths will no longer be able to be imported.

Reproduction Steps:

  • Write a sample script, eg:
import os
import sys
import numpy as np

sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'local_packages_path'))

import local_package as lp
  • Execute formatting.
  • Expected output:
import os
import sys
import numpy as np

sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'local_packages_path'))

import local_package as lp
  • Actual output:
import local_package as lp
import os
import sys
import numpy as np

sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'local_packages_path'))

Logs:

Click here for detailed logs 2024-12-30 18:07:54.892 [info] [Trace - 6:07:54 PM] Sending request 'textDocument/formatting - (3)'. 2024-12-30 18:07:54.896 [info] [Trace - 6:07:54 PM] Received notification 'window/logMessage'. 2024-12-30 18:07:54.896 [info] CONDA_PATH\anaconda3\envs\VENV_NAME\python.exe -m autopep8 - 2024-12-30 18:07:54.896 [info] [Trace - 6:07:54 PM] Received notification 'window/logMessage'. 2024-12-30 18:07:54.896 [info] CWD Server: REPO_PATH 2024-12-30 18:07:55.119 [info] [Trace - 6:07:55 PM] Received response 'textDocument/formatting - (3)' in 227ms. 2024-12-30 18:07:55.127 [info] [Trace - 6:07:55 PM] Sending notification 'textDocument/didChange'.

Outcome When Attempting Debugging Steps:

Did running it from the command line work?
Yes, but same output.

Extra Details

workingdir/
├── dir1/
    ├── main_script.py
├── local_packages_path/
    ├── local_package.py
  • Screenshots expected vs actual output:
  • Image
  • Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue identified by VS Code Team member as probable bugtriage-needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions