Can I overwrite the string form of a namedtuple?
Question:
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 ?
Answers:
You can define a function for it:
def print_loudness(self):
return str(self.loudness)
and assign it to __str__
:
Spoken.__str__ = print_loudness
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)
you can use code like this:
from collections import namedtuple
class SpokenTuple( namedtuple("Spoken", ["loudness", "pitch"]) ):
def __str__(self):
return str(self.loudness)
s = SpokenTuple(loudness=90, pitch='high')
print(str(s))
This will wrap namedtuple in a class of your choice which you then overload the str function too.
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 ?
You can define a function for it:
def print_loudness(self):
return str(self.loudness)
and assign it to __str__
:
Spoken.__str__ = print_loudness
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)
you can use code like this:
from collections import namedtuple
class SpokenTuple( namedtuple("Spoken", ["loudness", "pitch"]) ):
def __str__(self):
return str(self.loudness)
s = SpokenTuple(loudness=90, pitch='high')
print(str(s))
This will wrap namedtuple in a class of your choice which you then overload the str function too.