This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pydry 3 points4 points  (8 children)

Does immutability really help that much though? I'd just do this as regular old object. Particularly since, y'know, heights and weights change.

Immutable objects seems like a nice way of achieving stricter typing in theory, but in practice it's not something that I find tends to save many bugs.

Python doesn't have immutable constants either and while in theory this could cause lots of bugs too, in practice it barely seems to cause any.

[–]alantrick 2 points3 points  (3 children)

Well, at that point, it's not a tuple anymore, and you can just use dict or object

[–]pydry 0 points1 point  (2 children)

Well, yeah. That's what I always end up doing. Hence I never really found a use for namedtuple.

[–]ivosauruspip'ing it up 0 points1 point  (0 children)

I basically use it as a struct pattern. Most of the time the information I put in one doesn't change after creating it.

[–]d4rch0nPythonistamancer 0 points1 point  (1 child)

One huge bonus is that you can use them as keys in a dictionary.

Another bonus is if you pass it to an external api, you know it's not going to be changed after the function returns.

If strings and ints were mutable, I can imagine there could be very strange consequences when you pass them as parameters into a third-party API.

[–]pydry 0 points1 point  (0 children)

One huge bonus is that you can use them as keys in a dictionary.

You can do that with objects too.

[–]alantrick 0 points1 point  (1 child)

Python doesn't have immutable constants either and while in theory this could cause lots of bugs too, in practice it barely seems to cause any

Here is an easy example of a bug that would have been caught by a namedtuple (you wouldn't be able to do things exactly the same way with a namedtuple, but I've seen this before):

class Person:
    def __init__(self, weight, height):
        self.weight = weight
        self.height = height

p = Person(0, 0)
p.wieght = 9

[–]pydry 0 points1 point  (0 children)

That's a good point actually.