Skip to content

SONARPY-2864 Create rule S7510 The \"sorted\" function call should not be passed to the \"reversed\" function as an argument #5064

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions rules/S7510/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
23 changes: 23 additions & 0 deletions rules/S7510/python/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"title": "The \"sorted\" function call should not be passed to the \"reversed\" function as an argument",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "1min"
},
"tags": [
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7510",
"sqKey": "S7510",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
}
31 changes: 31 additions & 0 deletions rules/S7510/python/rule.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
This rule raises an issue when the `reversed()` function is called with a `sorted()` as an argument.

== Why is this an issue?

The `sorted()` function has a `reverse` parameter that provides the same functionality as the `reversed()` function.

== How to fix it
Use the `reverse` parameter of the `sorted()` function to sort in descending order instead of using `reversed()`.

=== Code examples

==== Noncompliant code example

[source,python,diff-id=1,diff-type=noncompliant]
----
data = [3, 1, 4, 1, 5, 9]
result = reversed(sorted(data)) # Noncompliant
----

==== Compliant solution

[source,python,diff-id=1,diff-type=compliant]
----
data = [3, 1, 4, 1, 5, 9]
result = sorted(data, reverse=True)
----

== Resources
=== Documentation
- Python reference documentation - https://docs.python.org/3/library/functions.html#sorted[sorted]
- Python reference documentation - https://docs.python.org/3/library/functions.html#reversed[reversed]