Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-like structures in Python

Tags:

python

struct

Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:

class MyStruct():     def __init__(self, field1, field2, field3):         self.field1 = field1         self.field2 = field2         self.field3 = field3 
like image 937
wesc Avatar asked Aug 30 '08 14:08

wesc


People also ask

What is the C struct equivalent in Python?

You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example). I think the "definitive" discussion is here, in the published version of the Python Cookbook. dF. dF.

Can we use structures in Python?

The struct module in Python is used to convert native Python data types such as strings and numbers into a string of bytes and vice versa. What this means is that users can parse binary files of data stored in C structs in Python.

How do you write structures in Python?

The method struct. pack() is used to convert the data types into bytes. It takes multiple arguments based on the first string. We have to pass the first string with format characters as mention in the above table.

Is struct in C similar to class in Python?

The big difference is that in Python (and other object oriented languages such as C++, Java, or C#), a class can also have functions associated with it that operate only on the instance of the class, whereas in C, a function that wishes to operate on a struct must accept the structure as a parameter in some way, ...


2 Answers

Update: Data Classes

With the introduction of Data Classes in Python 3.7 we get very close.

The following example is similar to the NamedTuple example below, but the resulting object is mutable and it allows for default values.

from dataclasses import dataclass   @dataclass class Point:     x: float     y: float     z: float = 0.0   p = Point(1.5, 2.5)  print(p)  # Point(x=1.5, y=2.5, z=0.0) 

This plays nicely with the new typing module in case you want to use more specific type annotations.

I've been waiting desperately for this! If you ask me, Data Classes and the new NamedTuple declaration, combined with the typing module are a godsend!

Improved NamedTuple declaration

Since Python 3.6 it became quite simple and beautiful (IMHO), as long as you can live with immutability.

A new way of declaring NamedTuples was introduced, which allows for type annotations as well:

from typing import NamedTuple   class User(NamedTuple):     name: str   class MyStruct(NamedTuple):     foo: str     bar: int     baz: list     qux: User   my_item = MyStruct('foo', 0, ['baz'], User('peter'))  print(my_item) # MyStruct(foo='foo', bar=0, baz=['baz'], qux=User(name='peter')) 
like image 174
Rotareti Avatar answered Sep 17 '22 19:09

Rotareti


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") 
like image 20
gz. Avatar answered Sep 21 '22 19:09

gz.