I have a bunch of methods which all look something like this:
def myFunc():
...
{initialise stuff}
{do stuff}
{finalise stuff}
...
where {initialise stuff}
and {finalise stuff}
are identical for each method, and {do stuff}
may use variables defined in {initialise stuff}
.
To avoid repetition, I'd like to put {initialise stuff}
and {finalise stuff}
in a separate method, which could be called from inside myFunc()
. So, something like this:
def wrap(innerMethod):
vars = {initialise stuff}
innerMethod(vars)
{finalise stuff}
def myFunc():
...
wrap(lambda vars :
{do stuff}
)
...
Unfortunately, it seems that code blocks can't be passed as arguments in Python (unless this feature has been added in the last 2 years). Therefore, this doesn't seem to work if {do stuff}
is longer than a single line. I could put {do stuff}
into a separate method, but I'd rather not since:
- The
{do stuff}
code will never be reused (it is different for each method); - It makes the program flow more confusing / less logical.
Is there another way to put {initialise stuff}
and {finalise stuff}
into a separate method?