Home > Enterprise >  Getting error when trying to create namedtuple object using _make function
Getting error when trying to create namedtuple object using _make function

Time:05-20

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

CodePudding user response:

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()])

CodePudding user response:

Your named tuple expects 5 tuple entries, however, you handed a list (which is one object) containing the last three entries. I modified your code (naming is awful, please change if you want to keep) and now it works.

Students = namedtuple('Student','Roll_No Name List_ofMarksPercentageGrad', defaults= 
[0,''])

As of now, I don't know any option to tell namedtuples that an entry is a list with named entries.

  • Related