News for hackers. Stuff that matters.
Re:Namedtuple in a Post-Dataclasses World by nikeee on Wednesday July 21, 2021 @11:35AM (#27907687)
There is also a NamedTuple (notice the different casing) from the typing library, which doesn't seem to be mentioned in the article:

https://docs.python.org/3/library/typing.html#typing.NamedTu...

    class Employee(NamedTuple):
        name: str
        id: int
This is equivalent to:

    Employee = collections.namedtuple('Employee', ['name', 'id'])
Re:Namedtuple in a Post-Dataclasses World by ziml77 on Wednesday July 21, 2021 @12:02PM (#27908016)
I like that method of defining a named tuple much more. I understand why it's required, but having to duplicate the name of the named tuple always bothered me. The type hints are excellent to have too.
Re:Namedtuple in a Post-Dataclasses World by Spivak on Wednesday July 21, 2021 @04:29PM (#27911720)
I don't know what you're talking about, I always confuse my coworkers by doing

    Pointe = namedtuple('Point'...
Re:Namedtuple in a Post-Dataclasses World by wizzwizz4 on Wednesday July 21, 2021 @04:43PM (#27911913)
This breaks pickle, among other things.
Re:Namedtuple in a Post-Dataclasses World by Spivak on Wednesday July 21, 2021 @05:06PM (#27912174)
It really shouldn't. This is actually an example of pickle being broken.

The class exists, there is an existing valid reference to it, and Python itself knows about it and the class itself knows its own name and namedtuple generates the right __getnewargs__. Everything is there for this to "just work" but pickle expects that every class object will have a reference to it of the same name which is kinda weird when you think about it.

You can see it with this stupid little program.

    from collections import namedtuple
    import pickle

    def get_all_subclasses(cls):
        all_subclasses = []

        for subclass in cls.__subclasses__():
            if subclass != type:
                all_subclasses.append(subclass)
                all_subclasses.extend(get_all_subclasses(subclass))

        return all_subclasses

     E = namedtuple('EEEEEEEEEEEEEEEEEEE', 'x')
     e = E(x='hello')

     for cls in get_all_subclasses(object):
          print(cls)

     pickle.dumps(e)
You'll that the class it there and called the right thing! But pickle tries to look up a reference to it under __main__.
Re:Namedtuple in a Post-Dataclasses World by wizzwizz4 on Friday July 23, 2021 @03:10PM (#27934456)
> but pickle expects that every class object will have a reference to it of the same name

Yeah: its qualname. The qualname, as per PEP 3155, is defined as:

> a dotted path leading to the object from the module top-level

so of course pickle can't cope with this information being incorrect. (How would you make it work?)

Re:Namedtuple in a Post-Dataclasses World by Spivak on Sunday July 25, 2021 @06:19PM (#27953469)
There’s a difference between the classes __qualname__ and the requirement that there be reference to the class at, say, __main__.$qualname as the way for pickle to actually find the class object.

This is the part that, to me, is really odd because pickle knows (in theory) the class and module name of the thing it needs to instantiate and the class objects themselves know their name and module.

Up to the lack efficiency actually doing this you could just enumerate all class objects to find the one with the right name and module name.

You get nested classes for free this way and you break the requirement that there be references to class objects of the same name in the module.

Re:Namedtuple in a Post-Dataclasses World by mikepurvis on Wednesday July 21, 2021 @12:22PM (#27908293)
That's awesome and I was not previously aware of it. Literally a decade ago I was asking on SO about exactly this kind of use-case [1] and at the time the answers were pretty unsatisfying; it's great to hear that the story is better now.

[1]: https://stackoverflow.com/questions/4071765/in-python-how-do...

Re:Namedtuple in a Post-Dataclasses World by Nagyman on Wednesday July 21, 2021 @11:58AM (#27907977)
It is mentioned if you expand the "In case you've never used them, here's a comparison." element.
Re:Namedtuple in a Post-Dataclasses World by colejohnson66 on Wednesday July 21, 2021 @11:42AM (#27907757)
I don’t use Python much, but what’s the difference between a NamedTuple and a regular class?
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)

Re:Namedtuple in a Post-Dataclasses World by masklinn on Wednesday July 21, 2021 @12:10PM (#27908120)
Well in and of itself none, in the sense that anything a namedtuple can do you could do by hand (it really just defines a class). However namedtuple:

* extends tuples, so a namedtuple is literally a tuple (which is useful)

* sets up a bunch of properties for the "named fields", which are basically just names on the tuple elements

* sets up a few other utility methods e.g. nice formatting, `_make`, `_asdict`, `_replace`

Now the latter two are nice, and mostly replicated by dataclasses (or attrs). The first one is the raison d'être of namedtuples though: originally their purpose is to "upgrade" tuple return values into richer / clearer types e.g. urlparse originally returned a 6-utple which is not necessarily super wieldy / clear, you can probably infer that the 3rd element is the path but… after upgrading to namedtuple it's just `result.path which is usually much clearer.

And because namedtuples are still classes in and of themselves, you can inherit from them to create a class with a `__dict__` with relative ease.

Re:Namedtuple in a Post-Dataclasses World by ZuLuuuuuu on Wednesday July 21, 2021 @11:54AM (#27907909)
NamedTuple has the features of a tuple, for example it is immutable. A regular class is mutable.
Re:Namedtuple in a Post-Dataclasses World by Spivak on Wednesday July 21, 2021 @04:46PM (#27911950)
I feel like none of the sibling answers actually answer your question which is "absolutely nothing." The function namedtuple is code generator that constructs a class definition and then eval()'s it.

The reason you reach for it is because it's tedious to write the same methods over and over to get things like a nice repr, methods covert between dicts, or pickling support.

The source from Python 3.6 is much more readable than 3.9 so I recommend reading that if you want to see how it works.

https://github.com/python/cpython/blob/3.6/Lib/collections/_...

Re:Namedtuple in a Post-Dataclasses World by palotasb on Wednesday July 21, 2021 @11:58AM (#27907963)
NamedTuple or namedtuple instances are tuple instances that have the same properties that regular tuples have. They are immutable (you cannot reassign their fields), you can index into them (a[0], a[1] instead of a.x and a.y), you can unpack them with *a. They can have methods like regular classes can, including additional @property methods. A NamedTuple class cannot inherit from another class, not even other named tuples.
Re:Namedtuple in a Post-Dataclasses World by akoumis on Wednesday July 21, 2021 @11:54AM (#27907905)
NamedTuple is purely a data container. It does not have class functions or a constructor you can use for anything other than setting the data members.
Re:Namedtuple in a Post-Dataclasses World by agumonkey on Wednesday July 21, 2021 @12:12PM (#27908140)
I think it was a pre-organized immutable data class in one line.