astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
29.93k stars 978 forks source link

`RUF011` possible false positive for optional unwrapping in dict comprehension #9548

Closed farmio closed 7 months ago

farmio commented 7 months ago

Hi 👋!

I have a piece of code raising

RUF011 Dictionary comprehension uses static key: `attr`

from ruff check . since the update from ruff 0.1.11 to 0.1.13.

This is the piece of code in question: https://github.com/XKNX/xknxproject/blob/73088e13bfcd11f4dc03963bf2c8ef4776972e68/xknxproject/loader/knx_master_loader.py#L70-L75 A short version of it:

from xml.etree.ElementTree import Element
translation_element: Element

translations = {
    attr: text
    for item in translation_element.findall("{*}Translation")  # `Element.findall() -> list[Element]`
    if (attr := item.get("AttributeName")) is not None  # unwrap since `Element.get() -> str | None`
    and (text := item.get("Text")) is not None
}

I would expect attr not to be treated as static key here since it should (depending on the xml source) be different for every iteration of the comprehension.

Here is my ruff section from pyproject.toml:

[tool.ruff]
target-version = "py39"
select = [
  "C4",  # comprehensions
  "D",   # pydocstyle
  "E",   # pycodestyle
  "F",   # pyflakes
  "I",   # isort
  "RUF", # ruff specific
  "T20", # print
  "UP",  # pyupgrade
  "W",   # pydocstyle warning
]
ignore = [
  "D202",
  "D203",
  "D212",
  "E501", # line too long
]
extend-exclude = [
  "script",
]

[tool.ruff.isort]
force-sort-within-sections = true
combine-as-imports = true
charliermarsh commented 7 months ago

Thanks! Looks like a bug.

charliermarsh commented 7 months ago

I'll fix this today.

charliermarsh commented 7 months ago

Oh sorry, I can confirm that this was already fixed on main but hasn't been released yet: https://github.com/astral-sh/ruff/pull/9494