Compare commits

...

2 Commits

Author SHA1 Message Date
Sebastian Zumbrunn
da38277c3f write initial rule draft 2024-11-12 17:33:25 +01:00
Seppli11
ef1e4fb887 Create rule S7160 2024-11-12 14:36:53 +00:00
3 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -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"
}
}

View File

@ -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