Why do you have to provide the typename as the first parameter when creating a namedtuple in Python -


this question has answer here:

in collections.namedtuple() constructor, first parameter name of type want create, far can tell, it's irrelevant aside diagnostic messages.

from collections import namedtuple point = namedtuple('point', 'x y') p = point(1,2)   # works fine, creates point(x=1, y=2)  point = namedtuple('blah', 'x y') p = point(2,3)   # works fine, creates blah(x=1,y=2) 

is necessary item programmer should keep consistent diagnostic purposes because there'd no way python learn name of variable you're assigning namedtuple to? seems error-prone, can see how it'd necessary. wondering if there other reasons or repercussions of mismatching these 2 names.

named tuples implemented in kind-of dirty way. there template string has few placeholders, , when call namedtuple() happens placeholders replaced arguments , template eval’d. implementation seems dirty (since uses eval) simple , powerful.

the downside there actual need class name because 1 of first lines this: class {typename}(tuple):. need specify type name work.

as value of name, not matter said yourself, debugging purposes, it’s useful choose same name use variable holds type. otherwise, whole thing wouldn’t different this:

class customtype:     …  # assign new name, , never talk customtype again newname = customtype 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -