kire
kire

Reputation: 95

How to simplify several functions with the same purpose

Let's say I have several functions that basically do the same thing but on a set of different variables. I think about something like that:

def changex():
    if x:
        # do procedure1 with x as variable
    else:
        # do procedure2 with x as variable

def changey():
    if y:
        # do procedure1 with y as variable
    else:
        # do procedure2 with y as variable

def changez():
    ...

How can I simplify that set of functions, such that I only have to write the function once but it does the job for all variables? I already looked into decorators which I think can do the job, but I can't make out how to make it work for my purpose.

Upvotes: 0

Views: 207

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114478

Decorators are way too complex for what you are trying to do. Functions can take arguments, so you can pass in the variable you want to do stuff with:

def change(var):
    if var:
        procedure1(var)
    else:
        procedure2(var)

Notice that I used if/else instead of checking both conditions with an if. I also recommend not testing explicitly against True/False. If you must do so, however, it is considered better practice to use is instead of == since True and False are singleton objects in Python: if x is True is better than if x == True.

Upvotes: 1

khelwood
khelwood

Reputation: 59186

Functions can accept variables as parameters.
Something like this:

def change(p):
    if p:
         # do procedure1 with p as variable
    else:
         # do procedure2 with p as variable

Then changex() becomes change(x); changey() becomes change(y) etc.

Upvotes: 3

Related Questions