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
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.
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.
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.
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, ...
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!
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'))
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With