Namedtuple - applications with different type names in one definition

The Python function namedtuple factory allows you to specify the name of the created subclass twice - first on the left side of the declaration, and then as the first argument of the function (IPython 1.0.0, Python 3.3.1):

 In [1]: from collections import namedtuple In [2]: TypeName = namedtuple('OtherTypeName', ['item']) 

All the examples I saw on docs.python.org use the same name in both positions. But you can use different names, and they work differently:

 In [3]: TypeName(1) Out[3]: OtherTypeName(item=1) In [4]: type(TypeName) Out[4]: builtins.type In [5]: type(OtherTypeName) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-8-6616c1214742> in <module>() ----> 1 type(OtherTypeName) NameError: name 'OtherTypeName' is not defined In []: OtherTypeName(1) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-47d6b5709a5c> in <module>() ----> 1 OtherTypeName(1) NameError: name 'OtherTypeName' is not defined 

I am wondering what applications might be for this feature.

+2
source share
1 answer

You do not specify a name twice. You specify one "internal" name when calling namedtuple, and then you assign the resulting namedtuple type to a variable.

The one you specify as an argument for namedtuple is the resulting type namedtuple, the native type of its name, that is, "what it calls." The thing to the left of the equal sign is a regular Python variable to which you assign the namedtuple type.

You can only use the created namedtuple if you assign it, and you can only use it by the name (s) that you assigned to it. Passing "OtherTypeName" as the "name" does not magically create a variable called OtherTypeName , so you are trying to use NameError when trying to use the name OtherTypeName . The only real use of the name passed in namedtuple ("OtherTypeName" in your case) is to display the resulting values.

Obviously, in many cases it is useful to have a variable that you use to refer to namedtuple, just like your own internal name; it makes things less confusing. But you can have several variables pointing to the same namedtuple:

 NameOne = namedtuple('OtherTypeName', ['item']) NameTwo = NameOne 

., or there are no variables pointing directly to it, and access it only through some container:

 x = [] x.append(namedtuple('OtherTypeName', ['item'])) x[0] # this is your namedtuple 

This is not so much that there are special โ€œapplicationsโ€ for this, since the behavior itself is not special: namedtuple is an object like any other, and creating an object is not the same as creating a variable that refers to it.

+2
source

All Articles