4

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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. Writing is more just an example. A more general question is how can I write the helper function that would use with statement and then call it from other functions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.