Python Forum
typename in collections.namedtuple
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
typename in collections.namedtuple
#1
does anyone know what collections.namedtuple's first argument, docs refer to as typename, is actually used for? i'm trying to figure out what i should put there.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
So to say - the name of the tuple, i.e. the typename
from collections import namedtuple

Foo = namedtuple('Bar', 'foo bar')
eggs = Foo(1, 3)
print(eggs)
Output:
Bar(foo=1, bar=3)
as you can see Foo is used for the instantiation, but the name (Bar) is the one provided as typename
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
gotcha, so it is creating a type. at a minimum each named tuple type name needs to be unique? does this namespace also need to avoid typenames of non-namedtuple types like "float"?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Don't know the answers for sure but lets check:

from collections import namedtuple
Spam = namedtuple('float', 'foo bar')
eggs = Spam(1, 2)
print(eggs)
print(type(eggs))
x = 1.2
print(type(x))
print(float('1.5'))

Spam2 = namedtuple('float', 'a, b')
eggs2 = Spam2(3, 4)
print(eggs)
print(eggs2)
Output:
float(foo=1, bar=2) <class '__main__.float'> <class 'float'> 1.5 (sbox) boyan@buranhome ~/sandbox2 $ /home/boyan/sandbox2/sbox/bin/python /home/boyan/sandbox2/enemy.py float(foo=1, bar=2) <class '__main__.float'> <class 'float'> 1.5 float(foo=1, bar=2) float(a=3, b=4)
It works but I would say it's confusing (both using built-in type as typename or using non-unique typename)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
what i would wonder is if there is any interference or collision with the the real float type.

and i have no plan to do other than use unique meaningful type names. i am looking over old functions to see what might get benefit from a named tuple.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020