Home > database >  Pythonic way to reuse code blocks in functions
Pythonic way to reuse code blocks in functions

Time:02-20

Is there a clean way to reuse code blocks in python classes to avoid having to retype the same code? For example lets say at the beginning of 2 different functions there is the same lines of code required to set up the function (where it is desired to keep the set up variables locally in the function).

def func1(path, x, y):
    img = load_img('path')
    img.normalize()
    foo = Foo(x)
    bar = Bar(y)

    **rest of the function (using img, foo and bar)

def func2(path, x, y):
    img = load_img('path')
    img.normalize()
    foo = Foo(x)
    bar = Bar(y)

    **different code here to func 1

Is there a standard best practice to set up the local variables to avoid code repetition? Like a function which can set local variables (maybe using nonlocal)? I know I could technically do the entire set up in a single function, however with a lot of input and output variables it might get a bit messy. I just wanted to see if there was a more elegant way to approach this, as ideally I'd just be able to call some arbitrary function which sets up the entire local space.

*Also just noting, I am aware I can wrap all the code in a class, turn the functions into methods and have shared attributes, however I don't think that's quite the right solution for this situation.

CodePudding user response:

Put the common code in another function that returns the values.

def common(path, x, y):
    img = load_img(path)
    img.normalize
    return img, Foo(x), Bar(y)

def func1(path, x, y):
    img, foo, bar = common(path, x, y)

    # different code

def func2(path, x, y):
    img, foo, bar = common(path, x, y)

    # different code

You might also consider using a decorator.

  • Related