Is there a way to get the string representation of a single NamedTuple
(or perhaps another type's) attribute?
The snippet below instantiates a pandas.Series
indexing a value using a str
key matching where the value came from.
If you later want to change the name of attr_1
to some_useful_attribute_name
, and want this reflected in the pandas series index, the code below requires two changes.
import pandas as pd
from typing import NamedTuple
class MyTuple(NamedTuple):
attr_1: int
attr_2: float
mt = MyTuple(1, 1)
ser = pd.Series(data=[mt.attr_1], index=['attr_1'])
People often miss the second change when the series instantiation is far away from the class definition.
Refactoring tools such as Pycharm's help somewhat, as they can identify all the attr_1
strings. However, if instead of attr_1
the string is more common, such as level
or whatever else, it becomes rather tedious to identify the correct strings to change.
Instead of the last line of code above I'd therefore like to do something like
ser = pd.Series(data=[mt.attr_1], index=[repr(mt.attr_1)])
except that of course repr()
doesn't give me the name of the attribute, but rather the string representation of its contents.
I am also aware of the NamedTuple._asdict()
method. However the use case here is one where only selected attributes go into the series rather than the entire dictionary.
EDIT: Might something be achieved by combining Enum and NamedTuple in a clever way?
Thanks for the help.