Search code examples
pythonpython-2.7python-object

Returning StringIO object


I have the following python code:

def parse_object(object):
    data = object.read()
    do_other_stuff(data)
def get_object():
    content = "abc"
    try:
        object = StringIO()
        object.write(content)
        return object
    finally:
        object.close()
def main():
    object = get_object()
    parse_object(object)

parse_object gets a file object or a StringIO instance, but obviously the StringIO object is getting closed as soon as get_object ends.
Is there a way of closing the object within get_object after it is being used?
parse_object cannot be altered because it is in a builtin library which I rather not change, get_object is in my code


Solution

  • In Python automatic closing is a typical work of context manager. See reference at https://docs.python.org/2.7/library/contextlib.html#contextlib.closing

    from contextlib import contextmanager
    
    
    def parse_object(object):
        data = object.read()
        do_other_stuff(data)
    
    @contextmanager
    def get_object():
        content = "abc"
        try:
            object = StringIO()
            object.write(content)
            yield object
        finally:
            object.close()
    
    def main():
        with get_object() as object:
            parse_object(object)