Function factory?

Peter Otten __peter__ at web.de
Wed Oct 24 13:04:02 EDT 2018


ftg at lutix.org wrote:

> Hello everyone,
> 
> I have 2 functions whose aim is to read a pdf file, the first one manages
> an uploaded file, the another one fecth a remote one (via an url). They
> are quite the same:
> ########################
> def handle_uploaded_file(path,file):
>     #if os.path.isfile(path + '/' + file.name):
>     #    file.name = '_' + file.name
> 
>     destination = open(path + '/' + file.name, 'wb+')
>     for chunk in file.chunks():
>         destination.write(chunk)
>     destination.close()
>     if check_file(path,file.name):
>         return True
>     else:
>         return False
> 
> def handle_remote_file(url,path,file_name=''):
>     if not file_name:
>         file_name = url.split('/')[-1]
> 
>     with urllib.request.urlopen(url) as response:
>         with open(path + '/' + file_name, 'wb+') as out_file:
>             shutil.copyfileobj(response, out_file)
>     if check_file(path,file_name):
>         return True
>     else:
>         return False
> ####################
> 
> I am wondering about the way I could rationalize those 2 functions.
> I have read about function factory and maybe it crosses my need.
> 
> Do you have some advices?

I don't see how a factory can help here; maybe you can instead factor out 
common code into a helper function? Example:

def handle_uploaded_file(fileobj, destfolder):
    return _handle_file(fileobj, destfolder, fileobj.name)

def handle_remote_file(url, destfolder):
    with urllib.request.urlopen(url) as response:
        return _handle_file(response, destfolder, url)

def _handle_file(instream, destfolder, filename):
    destfile = os.path.join(destfolder, posixpath.basename(filename))
    with open(destfile, "wb") as outstream:
        shutil.copyfileobj(instream, outstream)
    return check_file(destfile)





More information about the Python-list mailing list