I have the following two Python functions:
@classmethod
def serialize_dict(cls, d):
values = []
for column_name in cls().distinguishing_column_names():
value = str(d[column_name])
if value == 'None':
value = ''
values.append(value)
return ' '.join(values)
@classmethod
def serialize_row(cls, row):
values = []
for column_name in cls().distinguishing_column_names():
value = str(row.value(cls()._meta.db_table, column_name))
if value == 'None':
value = ''
values.append(value)
return ' '.join(values)
As you can see, the two functions are identical except for the first line of the for
loop. Not very DRY. How could I refactor this code to take out all the repetitions, given that row
and d
are of different types (dict
and a custom type of mine, respectively)?
Why don't you just implement the relevant bits of the dict
interface in your custom type?
So that row[column_name]
results in the code you want?
You use the __getitem__
special method for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With