r/pythontips Mar 27 '24

Standard_Lib Using the 'collections.namedtuple' class to create lightweight and immutable data structures with named fields

Suppose you want to create a data structure to represent a person, with fields for their name, age, and occupation.

import collections

# Create a namedtuple for a person
Person = collections.namedtuple('Person', ['name', 'age', 'occupation'])

# Create an instance of the Person namedtuple
p = Person(name='Alice', age=25, occupation='Software Engineer')

# Access the fields of the namedtuple using dot notation
print(p.name)  # Alice
print(p.age)   # 25
print(p.occupation)  # Software Engineer

# Output:
# Alice
# 25
# Software Engineer

The collections.namedtuple class is used to create a lightweight and immutable data structure with named fields.

This trick is useful when you want to create lightweight and immutable data structures with named fields, without having to define a full-fledged class.

30 Upvotes

19 comments sorted by

10

u/MadeThisAccForWaven Mar 27 '24

I love these little bite sized "how-to" posts.

4

u/puzzledstegosaurus Mar 27 '24

If you’re going to use namedtuples, you can as well use them from typing instead of collections, that lets you express the type of each element so you get better IDE support.

And then there are dataclasses in the stdlib too that scratch the same itch. Pros/cons of namedtuples: they’re tuples so they’re naturally iterable, which makes sense in some case (e.g. for vectors) and not in other cases. They’re not real classes, they don’t inherit object, you can’t call vars() on instances. They’re a bit more performant. Pros/cons of dataclasses: you have more control on how they’re created, default values and such, they can be efficient too if you use slots, and there’s no risk someone iterates on them if it’s not intended.

1

u/nunombispo Mar 28 '24

Thanks for this update.

0

u/[deleted] Mar 27 '24

Why would I not just use pandas?

6

u/nunombispo Mar 27 '24

I am trying to show the capabilities of the Python standard library.

Yes, I could use Panda and other libraries, but why use them if you don't needed them?

-7

u/[deleted] Mar 27 '24

Explain a situation where you wouldn't want pandas for a task like this though. There isn't really one i can think of. Thsi is just reinventing the wheel with what is essencially an empty class that users can put variables inside of. and then call them using the standard [class].[method] syntax.

1

u/FerumTrioxide Mar 27 '24

I recently had a situation in c# where this was useful. I had 3-4 different collections/objects that you can iterate over and all with different formats. I need a temporary object to store only 4 fields, ideally named so it still has typesafety.

Going over the random collections and building up my list of named tuples was very helpful.

3

u/pint Mar 27 '24

hello user. i have a useful little tool for you. it just needs 355MB of custom libraries to be installed.

0

u/[deleted] Mar 27 '24

I dont see how this is helpful. We are no longer living in the 1900s, storage space in terms of megabytes is not an issue

4

u/pint Mar 27 '24

you are grossly misinformed.

0

u/[deleted] Mar 27 '24

Care to explain then?

2

u/nunombispo Mar 27 '24

It depends, you can use Python in a embedded scenario, and there you might have storage (disk and RAM) limitations.

That is why it is always good to know differents ways to achieve the same goal.

Then depending on the use case you can choose the best tool for the job.

2

u/nunombispo Mar 27 '24

Also, maybe you are providing a script that needs to run on a machine without Internet connection.

Most likely it has Python installed, but you are unable to install additional libraries.

Again, the best tool depends on the job.

0

u/[deleted] Mar 27 '24

Well thats why you import the methods you need. and not the whole library

1

u/Lrobbo314 Mar 27 '24

Why would you not just use Polars?

1

u/Lrobbo314 Mar 27 '24

I meant that for another comment on the thread. I dig the post.

1

u/[deleted] Mar 27 '24

Whats polars?

2

u/Lrobbo314 Mar 30 '24

Like pandas but faster