I have code that looks like this:
from dataclasses import dataclass
@dataclass
class Example:
a: str
b: str
c: str
def repeated_code(self):
if self.c == 'A':
if self.a != "":
print(f"as {self.c = } and {self.a = }, set self.a to ''")
self.a = ""
if self.c == 'B':
if self.b != "":
print(f"as {self.c = } and {self.b = }, set self.b to ''")
self.b = ""
but I have many similar cases (> 10) in repeated code. I want to refactor this. I'm thinking about this:
@dataclass
class Example2:
a: str
b: str
c: str
def repeated_code(self):
if self.c == 'A':
if self.a != "":
self.log_and_set(self.a, "", self.c)
if self.c == 'B':
if self.b != "":
self.log_and_set(self.b, "", self.c)
def log_and_set(self, a, a_value, c):
print(f"as {c = } and {a = }, set {a} to ''")
a = a_value
But:
- Setting new value doesn't work in
log_and_set
(may be able to solve this, not too worried about this). - The printing is all wrong! I would like to print the
b
values when using theb
variable and thea
values otherwise, is there a way to do this using f-strings?