JDwum4
JDwum4

Reputation: 37

Unpacking a python tuple in a python function

Using Visual Studio & http://pythontutor.com/visualize I am unable to get the result for filesize function because of the following Error: TypeError: file_size() takes 1 positional argument but 3 were given. Code below.

#this function stores information about a file, its name, its type and its size in bytes.
def file_size(file_info):
    name, file_type, size = file_info
    return("{:.2f}".format(size/1024))

print(file_size('Class Assignment','docx', 17875)) #Should print 17.46
print(file_size('Notes','txt', 496)) #Should print 0.48
print(file_size('Program','py', 1239)) #Should print 1.21

I though unpacking (file_info) within the function will override the 1 positional argument but 3 were given error. What am I doing wrong?

Upvotes: 1

Views: 839

Answers (5)

TheDankMeister
TheDankMeister

Reputation: 1

If you want to keep the function with one parameter, try assigning the tuple to a variable and pass it in:

file_size(*varname)

Upvotes: 0

SSV 1
SSV 1

Reputation: 33

Please try this.

def file_size(file_info):

    (name,file_type,size)  = file_info
    return("{:.2f}".format( size/ 1024))

You need to pass file_info in a tuple in python.

Upvotes: 0

Sushant
Sushant

Reputation: 1

Please try this:

def file_size(file_info):
    name, type, size= file_info
    return("{:.2f}".format(size / 1024))

Upvotes: 0

Holden
Holden

Reputation: 642

Put the values into a tuple like this:

print(file_size(('Class Assignment','docx', 17875)))
print(file_size(('Notes','txt', 496)))
print(file_size(('Program','py', 1239)))

This way you are passing one variable

Upvotes: 1

donkopotamus
donkopotamus

Reputation: 23176

Currently you are passing three distinct arguments ... pass it instead as one argument which is a tuple:

print(file_size( ('Class Assignment','docx', 17875) ))

Alternatively, you could alter your function declaration to capture distinct arguments into a tuple when called:

def file_size(*file_info):
    ...

Then calling it as you are is valid.

Upvotes: 1

Related Questions