Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overwrite the string form of a namedtuple?

Tags:

python

For example:

>>> Spoken = namedtuple("Spoken", ["loudness", "pitch"]) >>> s = Spoken(loudness=90, pitch='high') >>> str(s) "Spoken(loudness=90, pitch='high')" 

What I want is:

>>> str(s) 90 

That is I want the string representation to display the loudness attribute. Is this possible ?

like image 517
canadadry Avatar asked Oct 27 '11 09:10

canadadry


People also ask

Can you change a Namedtuple?

Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field.

Is Namedtuple immutable?

A Python namedtuple is Immutable Like its regular counterpart, a python namedtuple is immutable. We can't change its attributes. To prove this, we'll try changing one of the attributes of a tuple of type 'Colors'.

How do I change attributes in Namedtuple?

Namedtuples are immutable objects, so you cannot change the attribute values.

Can you subclass Namedtuple?

As namedtuples are a subclass of tuples, the fields can be accessed via the index or by the name of the field. The index value of a field is tied to the order during the declaration of the namedtuple. Consider the above Address example. You can access the street field by name or by using 0 as the index value.


1 Answers

Yes, it is not hard to do and there is an example for it in the namedtuple docs.

The technique is to make a subclass that adds its own str method:

>>> from collections import namedtuple >>> class Spoken(namedtuple("Spoken", ["loudness", "pitch"])):         __slots__ = ()         def __str__(self):             return str(self.loudness)  >>> s = Spoken(loudness=90, pitch='high') >>> str(s) '90' 

Update:

You can also used typing.NamedTuple to get the same effect.

from typing import NamedTuple  class Spoken(NamedTuple):          loudness: int     pitch: str          def __str__(self):         return str(self.loudness) 
like image 102
Raymond Hettinger Avatar answered Sep 30 '22 17:09

Raymond Hettinger