namedtuples anamoly

Peter Otten __peter__ at web.de
Thu Oct 18 03:05:57 EDT 2018


Vinodhini Balusamy wrote:

> Hi,
> 
> I tried using namedtuples and just found a behaviour which I am not able
> to conclude as correct behaviour.
> 
> from collections import namedtuple
> 
> (n, categories) = (int(input()), input().split())
> Grade = namedtuple('Grade', categories)
> Grade.ID = 1
> #print(Grade.ID)
> ob = Grade(10, 50)
> print(ob.ID)
> print(ob.MARKS)
> ob1 = Grade(20, 100)
> print(ob1.ID)
> 
> 2
> ID MARKS
> 1
> 50
> 1
> 100
> 
> 
> If we set GRADE.ID =1 , it has impact on all variables. Is this behaviour
> just like class variable and it has global scope.

It's not *like* a class attribute, it *is* a class attribute.

> I expected ob.ID and ob1.ID to be 10.

You can access namedtuple members via name and via index. Indexed access is 
handled by the superclass (tuple), named access by properties. If you 
overwrite the property definition in the class with a value the property is 
lost and you'll see the value. 

There's a namedtuple feature that provides its source for you to explore. So 
see for yourself:

>>> namedtuple("Grade", "id marks", verbose=True)        
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict

class Grade(tuple):
    'Grade(id, marks)'

    __slots__ = ()

[snip]

    id = _property(_itemgetter(0), doc='Alias for field number 0')

    marks = _property(_itemgetter(1), doc='Alias for field number 1')


<class '__main__.Grade'>
>>>
 
> Correct me if Iam wrong.
> Appreciate any quick response.
> 
> Kind Rgds,
> Vinu





More information about the Python-list mailing list