
Improving your code readability with namedtuples - jaxondu
https://python-programming.courses/pythonic/improving-your-code-readability-with-namedtuples/
======
chronid
I would like to have this as a feature in the language without having to
import another "magic" module, something similar to case classes in Scala.

Let me dream :)

~~~
aw3c2
It's hardly a magic module, collections is part of the Python standard
library.
[https://docs.python.org/3/library/collections.html](https://docs.python.org/3/library/collections.html)

~~~
robohamburger
If you look at the code for it you will weep. If only python had hygienic
macros.

I would settle for better namedtuple syntax though.

~~~
rch
I always thought it was left as-is to further discussions about how it
_should_ be, without having to overcome a crowd of people claiming it's good
enough already.

------
kawera
On going discussion on reddit about this article/subject:
[https://www.reddit.com/r/Python/comments/3qw7m4/improving_yo...](https://www.reddit.com/r/Python/comments/3qw7m4/improving_your_code_readability_with_namedtuples/)

------
robohamburger
When you combine namedtuples with something like simplegeneric you can write
some pretty awesome functional code in python. I think of them not as just
tuples with names but something akin to an immutable struct.

I tend to reach for namedtuples first now over classes because of this (and
the fact that I don't do as much OOP in general).

------
svisser
One possible issue with this approach is that you may need to add methods in
the future to the tuple.

For example, the following pattern would improve code readability as well (by
making values available as attributes) but also allows you to extend it in the
future when you need to add additional methods to your object:

    
    
        class Person(object):
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)
    

Example: p = Person(name="John", age=30, weight=78) and p.age for access. When
needed you can add methods to this class while still keeping the code
readable.

~~~
orangecat
You can inherit from a namedtuple:

    
    
        class Person(namedtuple('Person', 'age weight height')):
            def is_adult(self):
                return self.age >= 18

~~~
js2
I would probably even annotate that method with @property. :-)

------
rch
I use namedtuples, and am happy to have them. What I dislike is the 'rename'
option and automatic conversion from whitespace or comma delimited field
names.

------
kdazzle
Not sure why you wouldn't just use a class in this case...

~~~
Scarblac
Immutability.

Both in a "eat your vegetables" sense (it's good in general to have immutable
data structures where possible, that's one cause of bugs eliminated), and for
practical reasons such as using them as keys of dictionaries, and as elements
of sets.

You can also _inherit_ from namedtuples, in case you want to add methods.

~~~
nottednelson
Yay, like locked named ranges in a basically-just-a-clunky-functional-
programming-environment spreadsheet. :)

------
whalesalad
namedtuples are a great feature of the language but this example could be
solved just as well with a dict. Like why is `person_data` not a dict?

The overall codebase used in this example is smelly.

~~~
watchdogtimer
It's easier and cleaner to write me.age instead of me['age'], especially when
you have an expression with a lot of brackets.

~~~
jamiesonbecker
I do like namedtuples also. I definitely agree -- dot-based access is handy!
Addict is a dict subclass that offers dot-based access (pip install addict)

Shortcomings are that it's not in stdlib and does have a few quirks (for
example, be sure to convert a Dict to a dict with .to_dict() before json'ing).
However, it's a nice and well maintained module.

------
acbart

        age, height, weight = person_data
    

Silly example for such a useful tool.

------
S4M
Named tuples are fine, but what do they have over using classes or
dictionaries?

~~~
kyzyl
Well, aside from being a different data structure with different
characteristics that will be more or less suitable for a given computation,
they share the same primary trait with vanilla tuples: they are immutable.

They also let you improve readability (as the article states), while being
full compatible with the ordinary tuple api. In other words, I can make a
named tuple where I think it will improve my own code, and then pass it into
someone else's code that is expecting a tuple and it will work. If you had
used a dict or somesuch in this scenario, you would have to do something to
marshall the state back into a tuple before you could pass the data into some
library that expects tuples, e.g. numpy or something.

------
seivan
You can name your tuples in Swift as well, I just wish more people did that.
It's increasingly annoying to get a tuple and have no clue what indices are
used for what.

------
glifchits
This is pretty great! I find myself writing classes to encapsulate small bits
of information, just to have this sort of functionality.

