Search code examples
pythoninstancenamedtuple

How can I get a named tuple instance from its name in python?


I have a set of named tuple instances. E.g.:

   CostFN = namedtuple('CostFN', ['name', 'func', 'args'])
   tuple_lin_1 = CostFN(name="lin_1", args=args_for_1, func1=func_1)
   tuple_lin_2 = CostFN(name="lin_2", args=args_for_1, func1=func_2)
   tuple_lin_3 = CostFN(name="lin_3", args=args_for_2, func1=func_1)
   tuple_lin_4 = CostFN(name="lin_4", args=args_for_2, func1=func_2)

I am saving the instance name, and I want to access the relevant instance from its name. Something like: my_tuple = CostFN.get("lin4") How do I achieve that?


Solution

  • You can't in any reasonable way. Objects don't have names in the way you think they do, names are bound to objects. So tuple_lin_4 is a name that contains a binding to the associated instance of CostFN, but the instance has no idea it's bound to that name. Similarly, the instance knows it is of type CostFN, but CostFN doesn't know about its own instances. So you've got two layers where the linkages don't work the way you intend.

    If looking up instances by name is an issue, I'd suggest making a dict mapping names to instances, rather than using individual named variables. If you really wanted to, you could do terrible things with a custom __new__ to cache instances by name on a dict tied to the class, but frankly, even that's going too far; you likely have an XY problem if you think you need a behavior like this at all.