diff --git a/rules/S7160/metadata.json b/rules/S7160/metadata.json new file mode 100644 index 00000000000..2c63c085104 --- /dev/null +++ b/rules/S7160/metadata.json @@ -0,0 +1,2 @@ +{ +} diff --git a/rules/S7160/python/metadata.json b/rules/S7160/python/metadata.json new file mode 100644 index 00000000000..a31e0769c43 --- /dev/null +++ b/rules/S7160/python/metadata.json @@ -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" + } +} diff --git a/rules/S7160/python/rule.adoc b/rules/S7160/python/rule.adoc new file mode 100644 index 00000000000..d80f19b6312 --- /dev/null +++ b/rules/S7160/python/rule.adoc @@ -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