Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, without method overloading, howto?

I want to write a function named size() which will accept either a file name or a list of filenames and return the size of the file or sum of its sizes respectively. How to do this without function overloading which is not available in python?

thanks

suresh

like image 496
suresh Avatar asked May 06 '26 11:05

suresh


2 Answers

def size(*files):
    for file in files:
        print file

*files is a special argument type which will catch all arguments into a list. Thus, if you call size like this:

size("file1.txt", "file2.xml")

files will be a list containing file1.txt and file2.xml. If you call it with only one argument, it will still be placed in a list.

To call the function with a list of files, use the same operator, but use in when you call the function:

file_list = ["file1.txt", "file2.xml"]
size(*file_list)
like image 66
Håvard Avatar answered May 07 '26 23:05

Håvard


I recommend using overloading internally as it is most intuitive to a user of the function

import os

def file_size(files):

    if isinstance(files, str):
        files = [files] # enlist

    size = 0
    for f in files:
        size += os.path.getsize(f)

    return size


if __name__ == '__main__':
    print file_size(__file__)
    print file_size([__file__, __file__])
    print file_size([])
like image 29
selvin Avatar answered May 08 '26 01:05

selvin