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
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)
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([])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With