Search code examples
pythonpython-3.xnamedtuple

Getting error when trying to create namedtuple object using _make function


Hi all I recently started learning Python collections module. When I was trying to implement namedtuple collections for practice I got an error. I tried searching for in the official Python documentation but could not find. Can you all please help me out.

The error I'm getting is that even though I'm specifying default values for some of my fields in namedtuple I'm getting

#Importing namedtuple from collections module
from collections import namedtuple

#Creating a Student namespace
Students = namedtuple('Student','Roll_No Name Marks Percentage Grad', defaults= 
[0,''])
Students._field_defaults

#Creating students
ram = Students._make([101,'Ram Lodhe',[95,88,98]])
shaym = Students._make([101,'Shyam Verma',[65,88,85]])
geeta = Students._make([101,'Geeta Laxmi',[86,90,60]])
venkat = Students._make([101,'Venkat Iyer',[55,75,68]])
ankita = Students._make([101,'Anikta Gushe',[88,90,98]])
 TypeError  Traceback (most recent call last)  
 ram = Students._make([101,'Ram Lodhe',[95,88,98]])  
 TypeError: Expected 5 arguments, got 3

Screenshot of Error


Solution

  • Per @jasonharper, _make() appears to bypass default values. So the fix is to construct the namedtuple directly:

    ram = Students(101,'Ram Lodhe',[95,88,98])
    

    Alternatively, you can manually pass the defaults to _make():

    ram = Students._make([101,'Ram Lodhe',[95,88,98], *Students._field_defaults.values()])