Enforcing Consistent Class Element Ordering in Ruff Linter #16051
Nickleaton
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
Thanks for the detailed write up and the rule proposal. I can see how a rule like this could be useful. I do agree that it will probably require a fair amount of configuration support to be useful for many projects. I also think that the rule requires an autofix, it's otherwise annoying for users if they have to reorder members manually We may want to consider adding such a rule in the future, but we don't plan on adding such an opinionated rule now because we first want to recategorize the rules (#1774) to make it easier for users to opt-in/opt-out to only correctness, idiomatic, or stylistic (like this) rule. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Proposal: Enforcing Consistent Class Element Ordering in Ruff Linter
Summary
Introduce a new Ruff linter rule to enforce a consistent ordering of class elements, ensuring readability, maintainability, and logical grouping of methods.
Motivation
Python developers often structure classes in a way that groups related methods together, improving code comprehension and reducing cognitive load. However, there is currently no built-in enforcement of method ordering, leading to inconsistencies across projects. This proposal defines a structured order that:
Rule Definition
1. Class Variables
Class-level variables should be declared first, before any methods.
2. Creation Methods
These methods should appear in the following order if present:
__init_subclass__
__init__
3. Public and Private Methods
Example:
4. Dunder Methods
Dunder methods should be grouped logically and ordered as follows:
Object Initialization & Destruction
__new__
__init__
__del__
String Representation
__repr__
__str__
__format__
__bytes__
Comparison & Ordering
__eq__
,__ne__
__lt__
,__le__
,__gt__
,__ge__
Arithmetic & Unary Operators
Bitwise Operators
In-Place Operators
Type Conversion & Casting
Attribute Access
Container & Sequence Protocol
Context Manager Methods
__enter__
before__exit__
Example:
Configuration Option
There should be an optional configuration setting that allows projects to define their preferred method ordering explicitly. This configuration would list method names in a specific order, which the linter would enforce. This ensures flexibility for teams with established conventions while maintaining consistency across subclasses.
Example configuration:
Implementation Details
Conclusion
This rule will standardize class structures, making Python codebases more consistent and readable, while still respecting developer intent.
Beta Was this translation helpful? Give feedback.
All reactions