pythonruff

How can I make "ruff check" assume a specific Python version for allowed syntax?


I am on Linux, created a Python 3.9 venv, installed ruff in the venv, wrote this code:

def process_data(data: list[int]) -> str:
    match data:
        case []:
            return "No data"
        case [first, *_] if (average := lambda: sum(data) / len(data)) and average() > 50:
            return f"Data average is high: {average():.2f}, starting with {first}"
        case _:
            return f"Processed {len(data)} items."

The match syntax is not available in Python 3.9, so running ruff check, I would expect an error. I have tried to set project.requires-python and ruff.target-version but the latter seems to be used only for the formatter according to the docs. What am I missing?


Solution

  • Ruff supports this since version 0.9.9 (but the rule is still in preview as of 0.11.2). See this issue for a list of supported constructs.

    $ ruff check a.py --target-version py39 --preview
    a.py:2:5: SyntaxError: Cannot use `match` statement on Python 3.9 (syntax was added in Python 3.10)
      |
    1 | def process_data(data: list[int]) -> str:
    2 |     match data:
      |     ^^^^^
    3 |         case []:
    4 |             return "No data"
      |
    
    Found 1 error.