News for hackers. Stuff that matters.
Re:Namedtuple in a Post-Dataclasses World by dec0dedab0de on Wednesday July 21, 2021 @12:02PM (#27908010)
a named tuple works exactly like a tuple, except you can also use names to get the items in it.

so it is immutable and you can get it via slicing.

  >>> from collections import namedtuple
  >>> Hat = namedtuple('Hat', ['style', 'size', 'color'])
  >>> my_hat = Hat('safari', 'XL', 'Orange')
  >>> my_hat
  Hat(style='safari', size='XL', color='Orange')
  >>> my_hat[0]
  'safari'
  >>> my_hat.color
  'Orange'
  >>> my_hat[1:]
  ('XL', 'Orange')
  >>> style, size, color = my_hat
  >>> size
  'XL'
  >>>

If thats all your using your classes for, then a named tuple is probably a better solution, or a dataclass. Though I normally just use dicts in that situation. If I see someone create a class without any methods, or atleast planned methods, I don't let it through code review.

EDIT: Also, Raymond Hettinger created named tuples. I'm not normally one for call to authority, or hero worship, but I am a huge fan of his. I recommend that anyone interested in Python should watch as many of his talks as they can.

EDIT2: As masklinn pointed out, another really good use of named tuples is when you're already returning a tuple, and you realize it would be better if it had names. You could change it to a named tuple without breaking any of the existing code. Unless they're doing something dumb like halfassing type checking at runtime. (this use case is in the article, which i didn't read at first)

There are no comments on this comment yet.