Reputation: 275
I have a few functions that use context manager:
def f1():
with open("test.txt","r+") as f:
f.write("common Line")
f.write("f1 Line")
def f2():
with open("test.txt","r+") as f:
f.write("common Line")
f.write("f2 Line")
def f3():
with open("test.txt","r+") as f:
f.write("common Line")
f.write("f3 Line")
These functions have a few common lines. So I want to add a helper function. Something like this
def helperF():
with open("test.txt","r+") as f:
f.write("common Line")
And then somehow call it from my f1,f2,f3 functions to make the code DRY.
But I'm not quite sure how to deal with context manager in this situation. The following will not work because f is already closed by the time the function is called:
def f1():
commonHelper()
f.write("f1 Line")
def f2():
commonHelper()
f.write("f2 Line")
def f3():
commonHelper()
f.write("f3 Line")
Upvotes: 4
Views: 259
Reputation: 51034
If the three functions are each writing quite a bit to the file, I would recommend refactoring so that they return a list of strings to be written, instead of having multiple functions which write directly to the file.
def write_with_common_header(lines):
with open("test.txt", "r+") as f:
f.write("common Line")
for line in lines:
f.write(line)
def f1():
return ["f1 Line"]
def f2():
return ["f2 Line"]
def f3():
return ["f3 Line"]
# usage example:
write_with_common_header(f2())
If the lists returned by each function will always be the same, then there is no need for them to even be functions; you can just declare them as lists.
In the more general case where the context manager isn't necessarily a file, and the separate functions are doing more than just calling a single method, then we can't just pass them in as data, but the same technique can be applied: make the write_with_common_header
function accept an argument so its behaviour can be parameterised. For full generality, the argument should be a function which accepts a reference to the managed resource f
.
def common_helper(callback):
with open("test.txt", "r+") as f:
f.write("common Line")
callback(f)
def f1(f):
f.write("f1 Line")
def f2(f):
f.write("f2 Line")
def f3(f):
f.write("f3 Line")
# usage example:
common_helper(f2)
Upvotes: 3