Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name from a named tuple in python?

Tags:

python

I create a named tuple like this:

from collections import namedtuple spam = namedtuple('eggs', 'x, y, z') ham = spam(1,2,3) 

Then I can access elements of ham with e.g.

>>> ham.x 1 >>> ham.z 3 

In the interpreter,

>>> ham eggs(x=1, y=2, z=3) 

But what if I just want to get 'eggs'? The only way I've been able to think of is

>>> ham.__repr__.split('(')[0] 'eggs' 

but this seems a bit messy. Is there a cleaner way of doing it?

Why do named tuples have this 'eggs' aspect to them if it isn't possible to access it without resorting to a private method?

like image 225
aaren Avatar asked Jun 07 '12 20:06

aaren


People also ask

How do you get a value from a named tuple?

The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

How do you use a name tuple?

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.

Can a named tuple be a dictionary key?

Yes, a tuple is a hashable value and can be used as a dictionary key. A tuple would be useful as a key when storing values associated with a grid or some other coordinate type system.


1 Answers

You can get the __name__ attribute of the class:

>>> type(ham).__name__ 'eggs' 

(Here using the type() builtin to get the class).

like image 147
Gareth Latty Avatar answered Sep 20 '22 12:09

Gareth Latty