Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What datatypes can a namedtuple contain in its fields?

I've looked at the Python documentation here on namedtuples and I can't seem to figure out what the legal data types are that it can take. Or perhaps it's not directly obvious to me.

Is it safe to say that it can take any datatypes (e.g. int, float, string, tuple, list, dict, etc)? Are there any data types that cannot be inserted into a namedtuple

This question arose from my need to have a namedtuple that has 2 lists. Essentially what i'm trying to do is is something like this:

from Collections import namedtuple

list1 = [23,45,12,67]
list2 = [76,34,56,23]

TwoLists = namedtuple("TwoLists", ['x','y'])
tulist = TwoLists(x=list1, y=list2)

type(tulist)
<class '__main__.TwoLists'>

type(tulist.x)
<class 'list'>

print(tulist.x)
[23,45,12,67]

print(tulist.y)
[76,34,56,23]

And this seems to work with at least with lists.

Some quick Googling didn't result in any examples, that's why i've added a code excerpt (from python's interactive mode) for any one else who tries to insert lists into a namedtuple and needs an example.

like image 813
Irvin H. Avatar asked Mar 14 '23 03:03

Irvin H.


2 Answers

Any python object is valid. If you want to force specific datatypes to the namedtuple, you can create a class that inherits from namedtuple with specified data types as follows (taken from https://alysivji.github.io/namedtuple-type-hints.html):

edit: note the below only works in python 3.6+

from typing import List, NamedTuple
class EmployeeImproved(NamedTuple):
    name: str
    age: int
    title: str
    department: str
    job_description: List
emma = EmployeeImproved('Emma Johnson',
                        28,
                        'Front-end Developer',
                        'Technology',
                        ['build React components',
                         'test front-end using Selenium',
                         'mentor junior developers'])

edit: in 3.5, you can do this:

import typing
EmployeeImproved = typing.NamedTuple("EmployeeImproved",[("name",str),("age",int),("title",str),("department",str),("job_description",List)])

.. and in 3.4 and earlier, I believe you are out of luck (someone correct me if I am wrong)

like image 162
Robert Meany Avatar answered Mar 20 '23 13:03

Robert Meany


Here is my attempt to answer based upon the documentation:

"Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index." from https://docs.python.org/3/library/collections.html#collections.namedtuple

"The items of a tuple are arbitrary Python objects" from https://docs.python.org/3/reference/datamodel.html#objects-values-and-types

like image 42
Mike Ulm Avatar answered Mar 20 '23 13:03

Mike Ulm