Anybody uses `ruff`? I'm trying to get it to sort ...
# general
h
Anybody uses
ruff
? I'm trying to get it to sort imports but it doesn't seem to work...
1
b
I use
ruff
a lot alongside Pants. What’s the issue that you’re running into?
h
It doesn't seem to care about imports other than removing unused ones Their documentation suggests they support
isort
but when I run both
fmt
and
fix
on these imports, nothing happens to them
Copy code
from pants.engine.goal import Goal

from typing import Type
import os
from pathlib import Path

from pants.base.build_root import BuildRoot
My
ruff.toml
is extremely bare-bones
Copy code
[format]
quote-style = "single"
b
Hmm yeah, I think that is related to this issue: https://github.com/pantsbuild/pants/issues/18410 You may need to add
pants
to the list of known-third-party modules to get the imports to sort properly
h
Interesting... I tried adding the following but it didn't work 😞
Copy code
[lint.isort]
known-third-party = ["pants"]
I also tried
fmt
and
fix
on a file with these imports (
example
is a first-party package:
Copy code
import numpy as np
import sys

import os
import example
b
Does adding
example
into the
known-first-party
ruff setting help?
h
Unfortunately not
I also tried commenting it out
I'm not crazy, right?
Copy code
import numpy as np
import sys

import os
This is not ordered
b
Yeah, definitely not. It should be:
Copy code
import os
import sys

import numpy as np
If you run
ruff
directly from the command line against the file, does it correctly resort the imports?
h
Okay it might be a
ruff
thing... 1. created a new venv 2. installed
ruff
3. ran
ruff format --config ruff.toml path/to/file.py
nothing happened 😮
b
Right, that’s what I was basically trying to figure out - is the issue in
ruff
or Pants? Looks like the former
h
It's not Pants-related now, but since we're at it, would you mind trying something? I tried creating a silly file
Copy code
import numpy
import os

import sys


os.path
sys
numpy
ruff
doesn't do anything to it Can you try the same with your config?
b
Hmm yup, can confirm. `ruff.toml`:
Copy code
[lint.isort]
known-third-party = ["numpy"]
`test.py`:
Copy code
import numpy
import os

import sys


os.path
sys
numpy
I then tried running:
ruff format --config ruff.toml test.py
and
ruff check --config ruff.toml --fix test.py
Neither command did anything
It looks like you have to opt into the behavior though: https://github.com/astral-sh/ruff/issues/8926
And indeed, when I add that same setting to my
ruff.toml
it works:
Copy code
[lint]
extend-select = ["I"]

# Note - still works even though I commented out these lines
#[lint.isort]
#known-third-party = ["numpy"]
h
Yes, looks like this is it
Voila!
pants fix
now produced
Copy code
import os
import sys

import numpy
🙌 1
Thanks @better-van-82973 🙂
b
All good, happy to help!