这是indexloc提供的服务,不要输入任何密码
Skip to content

Add autofix that adds from __future__ import annotations only when it would be useful #18502

@AlexWaygood

Description

@AlexWaygood

Summary

Several of Ruff's rules will be more aggressive in the diagnostics and autofixes they emit if from __future__ import annotations is enabled in the file:

For this reason, it's often useful to have from __future__ import annotations at the top of your Python file if you're running Ruff. Ruff knows that it can do a lot more with your code in these situations!

Ruff provides a lint rule FA100 that detects situations where UP035 or UP045 would make autofix edits if from __future__ import annotations was present, and complains that you should probably add that import. But this rule has two problems:

  • It does not have an autofix
  • It doesn't tackle situations where other rules such as the TC ones might make edits to your code if from __future__ import annotations were present in the module

Ruff provides a way to ensure that from __future__ import annotations is imported in every file in your project: you can use I002 in combination with the required-imports setting. But applying this to a large existing codebase might cause a huge diff with many unnecessary edits in it, which is probably undesirable.

I propose that we:

  • Add a configuration option to make FA100 more expansive, so that it also triggers in situations where the TC rules might make changes to your code if from __future__ import annotations was present.
    • I think this should be behind a configuration option, as the TC rules are very opinionated: not all users will want FA100 to also apply to these situations. Alternatively, we could add a new FA* rule that sits alongside FA100 and flags these situations -- this comment argues in favour of doing that instead.
  • Check to see if there are other rules where Ruff would be more aggressive if from __future__ import annotations were present. Should we have FA100 also flag modules where these other rules would make edits if from __future__ import annotations were present in the file?
  • Add an autofix to FA100 that auto-adds from __future__ import annotations

Metadata

Metadata

Assignees

Labels

fixesRelated to suggested fixes for violationsruleImplementing or modifying a lint rule

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions