Python function that accepts file object or path

前端 未结 2 1810
南笙
南笙 2020-12-30 05:23

I want to write a function that accepts either a path as a string or a file object. So far I have:

def awesome_parse(path_or_file):
    if isinstance(path_or         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 05:46

    The odd thing about your code is that if it is passed an open file, it will close it. This isn't good. Whatever code opened the file should be responsible for closing it. This makes the function a bit more complex though:

    def awesome_parse(path_or_file):
        if isinstance(path_or_file, basestring):
            f = file_to_close = open(path_or_file, 'rb')
        else:
            f = path_or_file
            file_to_close = None
        try:
            return do_stuff(f)
        finally:
            if file_to_close:
                file_to_close.close()
    

    You can abstract this away by writing your own context manager:

    @contextlib.contextmanager
    def awesome_open(path_or_file):
        if isinstance(path_or_file, basestring):
            f = file_to_close = open(path_or_file, 'rb')
        else:
            f = path_or_file
            file_to_close = None
    
        try:
            yield f
        finally:
            if file_to_close:
                file_to_close.close()
    
    def awesome_parse(path_or_file):
        with awesome_open(path_or_file) as f:
            return do_stuff(f)
    

提交回复
热议问题