Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn off Sort Imports for a selection of files, glob or similar in VS Code?

I am trying to Mock an import in python for a test. My code looks something like this.

"""Python file description."""

import sys
import pytest

import datetime as dt

from unittest.mock import Mock

sys.modules['module_A'] = Mock()

from module_to_test import function_to_test

where I need to mock module_A as a dependency for module_to_test.

On save, VSCode auto-orders this alphabetically, and as a result creates the Mock after it tries to import from the module with the dependency.

How do I prevent the Sort Imports from ordering a subset of files? This could be through a list of files, a glob, regex or similar?

Glob pattern of the test file ./tests/test_*.py.


Update - Partial solution posted below.

like image 301
Little Bobby Tables Avatar asked Dec 08 '22 12:12

Little Bobby Tables


2 Answers

If like mine your VSCode config is using isort (not autopep8) to do the import sorting, then you can override it on a selective basis like this:

app = Flask(__name__)
from . import views  # isort:skip

i.e. Add the # isort:skip comment to the import you don't want to jump to the top of the file.

Source: https://github.com/timothycrosley/isort#skip-processing-of-imports-outside-of-configuration

like image 187
cmuk Avatar answered Dec 28 '22 05:12

cmuk


VS Code runs autopep8 at save time and you can add the # noqa or # nopep8 comment at the end of a line to exclude that line from checking/sorting:

sys.modules['module_A'] = Mock()

from module_to_test import function_to_test # noqa
like image 25
mrts Avatar answered Dec 28 '22 05:12

mrts