Python function that accepts file object or path

前端 未结 2 1818
南笙
南笙 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 06:11

    You could do:

    def awesome_parse(do_stuff):
        """Decorator to open a filename passed to a function
           that requires an open file object"""
        def parse_path_or_file(path_or_file):
            """Use a ternary expression to either open the file from the filename
               or just pass the extant file object on through"""
            with (open(path_or_file, 'rb') 
                   if isinstance(path_or_file, basestring) 
                    else path_or_file) as f:
                return do_stuff(f)
        return parse_path_or_file
    

    And then when you declare any function that does stuff on an open file object:

    @awesome_parse
    def do_things(open_file_object):
        """This will always get an open file object even if passed a string"""
        pass
    
    @awesome_parse
    def do_stuff(open_file_object):
        """So will this"""
        pass
    

    Edit 2: More detailed info on the decorator.

提交回复
热议问题