7 ms·
Improving your code readability with namedtuples
- S4M 11y agoNamed tuples are fine, but what do they have over using classes or dictionaries?
- kyzyl 11y agoWell, 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.
- chronid 11y agoI 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 :)
- 0x0dea 11y agoRuby's Struct is pretty nifty. Person = Struct.new :name, :age people = [ Person.new('Alice', 42), Person.new('Bob', 23), Person.new('Carol', 30) ] people.sort_by(&:age).map(&:name) # => ["Bob", "Carol", "Alice"]
- aw3c2 11y agoIt'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
- maxerickson 11y agoIt's kind of magical: https://hg.python.org/cpython/file/tip/Lib/collections/__init__.py#l284 https://hg.python.org/cpython/file/tip/Lib/collections/__ini...
- robohamburger 11y agoIf 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 11y agoI 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.
- whalesalad 11y agonamedtuples 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.
- jdiez17 11y agonamedtuples are supposedly more space-efficient. For one, you don't have to store the keys every time.
- deleted 11y ago[deleted]
- watchdogtimer 11y agoIt's easier and cleaner to write me.age instead of me['age'], especially when you have an expression with a lot of brackets.
- nostrademons 11y agoAlso a better upgrade path to a "real" class-based solution.
- jamiesonbecker 11y agoI 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.
- Scarblac 11y agoAt work I'm the guy who's always saying that overuse of dictionaries is a code smell. What keys does the dictionary "person_data" have? Well, originally it only contained username and email address, later we added street address (everywhere where it was used, we think). And then came preferred language, but that was only added in the functions that care about that. And so on, and so forth... Eventually all functions work with a slightly different version of a person_data dict, you're never quite sure which one a given function expects, and there is no central definition. Death by duck typing. Dicts are for algorithms, they shouldn't be the go-to tool for structs of data. That's what classes and namedtuples are for.
- svisser 11y agoOne 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.
- chubot 11y agoIf you're going to do that, might as well just spell out the members, although it's verbose. What you're doing doesn't check that the attributes are valid.
- raverbashing 11y agoless readable, but you only need: self.__dict__.update(kwargs)
- detaro 11y agoThen you can replace the namedtuple with a custom class in the future.
- orangecat 11y agoYou can inherit from a namedtuple: class Person(namedtuple('Person', 'age weight height')): def is_adult(self): return self.age >= 18
- js2 11y agoI would probably even annotate that method with @property. :-)
- js2 11y agoYou can subclass namedtuple: class Foo(namedtuple("Foo", "a b c")): __slots__ = () def abc(self): return self.a + self.b + self.c
- acbart 11y agoage, height, weight = person_data Silly example for such a useful tool.
- kdazzle 11y agoNot sure why you wouldn't just use a class in this case...
- maxerickson 11y agocollections.namedtuple is just a factory for a particular sort of class.
- Scarblac 11y agoImmutability. 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 11y agoYay, like locked named ranges in a basically-just-a-clunky-functional-programming-environment spreadsheet. :)
- kawera 11y agoOn going discussion on reddit about this article/subject: https://www.reddit.com/r/Python/comments/3qw7m4/improving_your_code_readability_with_namedtuples/ https://www.reddit.com/r/Python/comments/3qw7m4/improving_yo...
- deleted 11y ago[deleted]
- seivan 11y agoYou 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 11y agoThis is pretty great! I find myself writing classes to encapsulate small bits of information, just to have this sort of functionality.
- robohamburger 11y agoWhen 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).
- rch 11y agoI 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.