Skip to content
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

Create rule S7160 #4495

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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/S7160/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
23 changes: 23 additions & 0 deletions rules/S7160/python/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"title": "Dataclasses should be recreated using \"dataclasses.replace\"",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7160",
"sqKey": "S7160",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
}
59 changes: 59 additions & 0 deletions rules/S7160/python/rule.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
== Why is this an issue?

Instead of manually recreating dataclasses, ``++dataclasses.replace(...)++`` can be used to recreate dataclasses with modified values.

Alternatively, the in Python 3.13 introduced, more general-purpose ``++copy.replace(...)++`` can be used to archive the same result.


== How to fix it

=== Code examples

==== Noncompliant code example

[source,python,diff-id=1,diff-type=noncompliant]
----
from dataclasses import dataclass

@dataclass
class Point:
x: int
y: int

p1 = Point(1, 2)
p2 = Point(p1.x, 3) # Noncompliant
----

==== Compliant solution

[source,python,diff-id=1,diff-type=compliant]
----
from dataclasses import dataclass
import dataclasses
import copy

@dataclass
class Point:
x: int
y: int

p1 = Point(1, 2)
p2 = dataclasses.replace(p1, y=3) # Compliant
p3 = copy.replace(p1, y=3) # Compliant
----

//=== Pitfalls

//=== Going the extra mile


== Resources
=== Documentation

* https://docs.python.org/3/library/dataclasses.html#dataclasses.replace
* https://docs.python.org/3/library/copy.html#copy.replace
//=== Articles & blog posts
//=== Conference presentations
//=== Standards
//=== External coding guidelines
//=== Benchmarks
Loading