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)?
Add an
if isinstance(arg, dict)to determine whether to treat it as a row or dict, then merge the two methods together.