r/Python • python-programming.courses • Oct 30 '15

Improving your code readability with namedtuples

https://python-programming.courses/pythonic/improving-your-code-readability-with-namedtuples/
186 Upvotes

79 comments sorted by

View all comments

Show parent comments

4

u/[deleted] Oct 31 '15

[removed] — view removed comment

3

u/alantrick Oct 31 '15

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

1

u/[deleted] Oct 31 '15

[removed] — view removed comment

1

u/ivosaurus pip'ing it up Nov 02 '15

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

1

u/d4rch0n Pythonistamancer Oct 31 '15

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.

1

u/alantrick Oct 31 '15

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