How do I get the name from a named tuple in python?
Question:
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?
Answers:
You can get the __name__
attribute of the class:
>>> type(ham).__name__
'eggs'
(Here using the type()
builtin to get the class).
>>> ham.__class__.__name__
'eggs'
Based on python’s doc, namedtuple
gives you a new tuple subclass named ‘eggs’
So essentially you need the class name
and type(ham).__name__
will give you the class name
On the topic of namedtuple attributes:
>>> ham._fields
('x', 'y', 'z')
is sometimes useful to know
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?
You can get the __name__
attribute of the class:
>>> type(ham).__name__
'eggs'
(Here using the type()
builtin to get the class).
>>> ham.__class__.__name__
'eggs'
Based on python’s doc, namedtuple
gives you a new tuple subclass named ‘eggs’
So essentially you need the class name
and type(ham).__name__
will give you the class name
On the topic of namedtuple attributes:
>>> ham._fields
('x', 'y', 'z')
is sometimes useful to know