Is there a data type in Python similar to structs in C++?

Solution 1:

Why not? Classes are fine for that.

If you want to save some memory, you might also want to use __slots__ so the objects don't have a __dict__. See http://docs.python.org/reference/datamodel.html#slots for details and Usage of __slots__? for some useful information.

For example, a class holding only two values (a and b) could looks like this:

class AB(object):
    __slots__ = ('a', 'b')

If you actually want a dict but with obj.item access instead of obj['item'], you could subclass dict and implement __getattr__ and __setattr__ to behave like __getitem__ and __setitem__.

Solution 2:

In addition to the dict type, there is a namedtuple type that behaves somewhat like a struct.

MyStruct = namedtuple('MyStruct', ['someName', 'anotherName'])
aStruct = MyStruct('aValue', 'anotherValue')

print aStruct.someName, aStruct.anotherName