Closing files/streams etc

I made a function that returns a stream IO object containing text from a string input, with some exception handling.

My question is: how do I make sure the stream gets closed? The function needs to return the stream object.

I don’t know if I close it in the calling function, will it close the original or just a copy.

I’m somewhat new to Python, so if I did this totally wrong then please feel free to tear it apart. I want to learn.

I’ve read that using ‘with’ is favored instead of ‘try’, but I’m not sure how I would implement that into my context.

Thank you.

def make_stream(input_string:str):

    output_stream = io.StringIO()

    while not output_stream.getvalue():    
        try:
            output_stream = io.StringIO(input_string)
        except (OSError, MemoryError):
            print("A system error occurred creating text io stream. Exiting.")
            raise SystemExit(1)
        except (UnicodeEncodeError, UnicodeDecodeError, TypeError):
            print ("Input text error creating io stream. Exiting.")
            raise SystemExit(1)
        finally:
            logging.info (" Input stream created successfully.")

    return output_stream

Only the last stream is returned. First of all a stream is used to start the while loop. Then a new one is created every iteration of that. Is this really the intention?

So you still need to call .close on streams 1, …, N-1 in the function body. Even if doing so’s less critical for an in memory StringIO object (than for files and DB connections etc.), I would just rethink the whole thing.

The except blocks aren’t adding value for me. You’re raising SystemExit(1) anyway, so instead I would just simply let it crash:

def make_stream(input_string:str):
    return io.StringIO(input_string)
1 Like