user3675188
user3675188

Reputation: 7409

How can I reduce the duplicated use of if and else

How can I use decorator or what else elegant way to avoid lots of if else logic in my functions

class DataModification():
    @classmethod
    def schedule(cls, df):
        if df.empty:
            return df
        else:
            df.rename(columns={'_id':'release_id'}, inplace=True)
            df.set_index("release_id", drop=True, inplace=True)
            df.rename(columns={'is_projection':'projections_available'}, inplace=True)
            df.rename(columns={'is_statement':'statement_available'}, inplace=True)
            return df.sort_index()

    @classmethod
    def function_b(cls, df):
        if df.empty:
            return df
        else:
            df.rename(columns={'_id':'release_id'}, inplace=True)
            df.set_index("release_id", drop=True, inplace=True)
            return df.sort_index()   

Upvotes: 2

Views: 76

Answers (1)

André Laszlo
André Laszlo

Reputation: 15537

Both methods could be rewritten to something like this:

@classmethod
def function_b(cls, df):
    if df.empty:
        return df
    df.rename(columns={'_id':'release_id'}, inplace=True)
    df.set_index("release_id", drop=True, inplace=True)
    return df.sort_index()

Since the first return would make sure that the code in the else block doesn't run if the ifs condition is True.

This is just two lines that you see everywhere in Python code - so I don't think a decorator is necessary. It just adds complexity and gives you one line less code for each function. If you are counting lines, you could also write:

if df.empty: return df

It's a bit less readable, in my opinion.


Try writing the decorator as an exercise. I think it should work like this:

class Foo:
    @return_empty
    def bar(self, df):
        print "Not empty: %s" % df

class Test(set):
    @property
    def empty(self):
        return len(self) == 0

>>> f = Foo()    
>>> t = Test()   
>>> f.bar(t)
set()
>>> t.add(1)
>>> f.bar(t)
Not empty: Test([1])

Spoiler

def return_empty(f): def _wrapper(self, df): if df.empty: return df return f(self, df) return _wrapper

Upvotes: 2

Related Questions