A Peer-to-Peer Learning Community for Python Enthusiasts…Just Like You PythonistaCafe is an invite-only, online community for Pythonistas helping each other succeed and grow » Learn more at PythonistaCafe.com
Writing Clean Python With Namedtuples
By Dan Bader — Get free updates of new posts here.
Python comes with a specialized “namedtuple” container type that doesn’t seem to get the attention it deserves. It’s one of these amazing features in Python that’s hidden in plain sight.
Namedtuples can be a great alternative to defining a class manually and they have some other interesting features that I want to introduce you to in this article.
Now, what’s a namedtuple and what makes it so special? A good way to think about namedtuples is to view them as an extension of the built-in tuple data type.
Python’s tuples are a simple data structure for grouping arbitrary objects. Tuples are also immutable—they cannot be modified once they’ve been created.
>>>tup=('hello',object(),42)>>>tup('hello',<objectobjectat0x105e76b70>,42)>>>tup42>>>tup=23TypeError:"'tuple' object does not support item assignment"
A downside of plain tuples is that the data you store in them can only be pulled out by accessing it through integer indexes. You can’t give names to individual properties stored in a tuple. This can impact code readability.
Also, a tuple is always an ad-hoc structure. It’s hard to ensure that two tuples have the same number of fields and the same properties stored on them. This makes it easy to introduce “slip-of-the-mind” bugs by mixing up the field order.
The Meaning of Underscores in Python – The various meanings and naming conventions around single and double underscores (“dunder”) in Python, how name mangling works and how it affects your own Python classes.
Python Iterators: A Step-By-Step Introduction – Understanding iterators is a milestone for any serious Pythonista. With this step-by-step tutorial you’ll understanding class-based iterators in Python, completely from scratch.
Improve Your Python with 🐍 Python Tricks 💌 Get a short & sweet Python code snippet delivered to your inbox every couple of days: » Click here to see examples
Working With File I/O in Python – Learn the basics of working with files in Python. How to read from files, how to write data to them, what file seeks are, and why files should be closed.
How to Reverse a String in Python – An overview of the three main ways to reverse a Python string: “slicing”, reverse iteration, and the classic in-place reversal algorithm. Also includes performance benchmarks.
🐍🐍 Peer-to-Peer Learning for Pythonistas PythonistaCafe is an invite-only, online community of Python and software development enthusiasts helping each other succeed and grow: » Learn more at pythonistacafe.com