Another way of doing structs

Instead of using an “on-the-fly” lambda abomination, I already showed why I think creating a class is easier. But there’s another, even simpler way for C-style structs: the named tuple.

The downsides of the named tuple are that, unlike an “empty” object, you can’t add attributes to it later; and it requires an import. On the upside: a much shorter definition.

Here’s how it works:

# named tuple demo
from collections import namedtuple

# instead of a class definition: tadaa!
Geo = namedtuple('Geo', 'lat, lon')

# using the named tuple
my_town = Geo(47.6, -45.8)
print(my_town.lat, my_town.lon)
print(my_town)

You get the best of both worlds; only one line to define your “struct” and only one line to create it. Even better, it will behave like a tuple where needed.

Downsides: an extra line to import something (but it’s from a standard library, so no big deal), and, it being a tuple, you cannot alter the attributes. But in those cases where it doesn’t matter, it’s a great solution!

 

Leave a comment