Open filename, or do nothing if filename is already an open file object

def opened(filename, mode):
    "Open filename, or do nothing if filename is already an open file object"
    if isinstance(filename, str):
        file = open(filename, mode)
        try: 
            yield file
        finally: 
            if not file.closed:
                file.close()
    else:
        yield filename