Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refactor these two functions to be more DRY?

Tags:

python

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)?

like image 997
Jason Swett Avatar asked Dec 17 '22 16:12

Jason Swett


1 Answers

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.

like image 149
Daren Thomas Avatar answered Jan 05 '23 02:01

Daren Thomas