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")