C-like structures in Python

Use a named tuple, which was added to the collections module in the standard library in Python 2.6. It’s also possible to use Raymond Hettinger’s named tuple recipe if you need to support Python 2.4.

It’s nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:

from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")

The newly created type can be used like this:

m = MyStruct("foo", "bar", "baz")

You can also use named arguments:

m = MyStruct(field1="foo", field2="bar", field3="baz")

Leave a Comment