user9721253
user9721253

Reputation:

How can make this code DRY?

Is there a way to avoid repetition in the following code:

is_on = True

def func1():
    global is_on
    if is_on:
        pass

def func2():
    global is_on
    if is_on:
        pass

def func3():
    global is_on
    if is_on:
        pass

I am using Python 3.6.5

Edit: each func has a code to be executed when they are called (instead of pass), but only if the variable is_on evaluate to True, this variable can be changed by another code so that when these func are called they wont do anything. Sorry if this is confusing.

Upvotes: 2

Views: 133

Answers (1)

Rohi
Rohi

Reputation: 814

Im guessing you want all the functions to start by doing the same things and then do something else, if this is the case you should use a decorator.

Try using a decorator

@some_decorator
def some_func():
    # Do something


def some_decorator(func):
    def new_function(*args):
        if (not is_on):
            return
        func_result = func(*args)
        return func_result
    return new_function

Basically what happens here is every time some_func is called it receives a new function object from the decorator which tests your request and calls the function if the 'if' statement is true.

Also as stated in the comments no reason to use global, since there is no other variable with the same name.

Upvotes: 3

Related Questions