Python Forum
typename in collections.namedtuple - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: typename in collections.namedtuple (/thread-23292.html)



typename in collections.namedtuple - Skaperen - Dec-20-2019

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.


RE: typename in collections.namedtuple - buran - Dec-20-2019

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


RE: typename in collections.namedtuple - Skaperen - Dec-21-2019

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"?


RE: typename in collections.namedtuple - buran - Dec-21-2019

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)


RE: typename in collections.namedtuple - Skaperen - Dec-22-2019

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.