Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relevance of typename in namedtuple

from collections import namedtuple  Point = namedtuple('whatsmypurpose',['x','y']) p = Point(11,22) print(p) 

Output:

whatsmypurpose(x=11,y=22) 

What's the relevance/use of 'whatsmypurpose'?

like image 907
Phoenix Avatar asked Mar 31 '14 13:03

Phoenix


People also ask

What is Typename in Namedtuple?

typename provides the class name for the namedtuple returned by namedtuple() . You need to pass a string with a valid Python identifier to this argument. field_names provides the field names that you'll use to access the values in the tuple.

What is an advantage of Namedtuples over dictionaries?

Moreover, as namedtuple instances do not have per-instance dictionaries, they are lightweight and require no more memory than regular tuples. This makes them faster than dictionaries.

Are named tuples useful?

Even though named tuples are rarely used, are still quite powerful. This particular extension data type shares characteristics from built-in tuples, dictionaries and even classes. Named tuples are usually useful when we need to build data structures that can be accessed both by positional indices or attribute names.

What's the advantage of using Namedtuple instead of tuple?

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.


2 Answers

namedtuple() is a factory function for tuple subclasses. Here, 'whatsmypurpose'is the type name. When you create a named tuple, a class with this name (whatsmypurpose) gets created internally.

You can notice this by using the verbose argument like:

Point=namedtuple('whatsmypurpose',['x','y'], verbose=True) 

Also you can try type(p) to verify this.

like image 111
haraprasadj Avatar answered Sep 28 '22 05:09

haraprasadj


'whatsmypurpose' gives the new subclass its type name. From the docs:

collections.namedtuple(typename, field_names, verbose=False,rename=False)
Returns a new tuple subclass named typename.

Here is an example:

>>> from collections import namedtuple >>> Foo = namedtuple('Foo', ['a', 'b']) >>> type(Foo) <class 'type'> >>> a = Foo(a = 1, b = 2) >>> a Foo(a=1, b=2) >>> Foo = namedtuple('whatsmypurpose', ['a', 'b']) >>> a = Foo(a = 1, b = 2) >>> a whatsmypurpose(a=1, b=2) >>>  

Set the verbose parameter to True and you can see the complete whatsmypurpose class definition.

>>> Foo = namedtuple('whatsmypurpose', ['a', 'b'], verbose=True) from builtins import property as _property, tuple as _tuple from operator import itemgetter as _itemgetter from collections import OrderedDict  class whatsmypurpose(tuple):     'whatsmypurpose(a, b)'      __slots__ = ()      _fields = ('a', 'b')      def __new__(_cls, a, b):         'Create new instance of whatsmypurpose(a, b)'         return _tuple.__new__(_cls, (a, b))      @classmethod     def _make(cls, iterable, new=tuple.__new__, len=len):         'Make a new whatsmypurpose object from a sequence or iterable'         result = new(cls, iterable)         if len(result) != 2:             raise TypeError('Expected 2 arguments, got %d' % len(result))         return result      def _replace(_self, **kwds):         'Return a new whatsmypurpose object replacing specified fields with new values'         result = _self._make(map(kwds.pop, ('a', 'b'), _self))         if kwds:             raise ValueError('Got unexpected field names: %r' % list(kwds))         return result      def __repr__(self):         'Return a nicely formatted representation string'         return self.__class__.__name__ + '(a=%r, b=%r)' % self      def _asdict(self):         'Return a new OrderedDict which maps field names to their values.'         return OrderedDict(zip(self._fields, self))      def __getnewargs__(self):         'Return self as a plain tuple.  Used by copy and pickle.'         return tuple(self)      a = _property(_itemgetter(0), doc='Alias for field number 0')      b = _property(_itemgetter(1), doc='Alias for field number 1') 
like image 33
wwii Avatar answered Sep 28 '22 06:09

wwii