Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Daniel Bader: Writing Clean Python With Namedtuples

$
0
0

Daniel Bader: Writing Clean Python With Namedtuples

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', <object object at 0x105e76b70>, 42) >>> tup[2] 42 >>> tup[2] = 23 TypeError: "'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.


Viewing all articles
Browse latest Browse all 9596

Trending Articles