Can we use structure in python?
Asked 14 years, 1 month ago
Viewed 766k times
Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
asked Aug 30, 2008 at 14:33
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.
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:
answered Jul 31, 2017 at 22:54
43.6k19 gold badges104 silver badges102 bronze badges
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:
The newly created type can be used like this:
You can also use named arguments:
answered Aug 30, 2008 at 15:18
6,5611 gold badge22 silver badges34 bronze badges
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).
For everything else you can use dictionary, or a utility class like this one:
I think the "definitive" discussion is here, in the published version of the Python Cookbook.
382k180 gold badges944 silver badges1616 bronze badges
answered Aug 30, 2008 at 14:38
72.2k29 gold badges128 silver badges135 bronze badges
Perhaps you are looking for Structs without constructors:
answered Sep 21, 2010 at 15:15
How about a dictionary?
Something like this:
Then you can use this to manipulate values:
And the values don't have to be strings. They can be pretty much any other object.
answered Aug 30, 2008 at 14:35
Mark BiekMark Biek
143k54 gold badges155 silver badges200 bronze badges
You can access the fields of a class using a dictionary because the fields of a class, its methods and all its properties are stored internally using dicts (at least in CPython).
...Which leads us to your second comment. Believing that Python dicts are "heavy" is an extremely non-pythonistic concept. And reading such comments kills my Python Zen. That's not good.
You see, when you declare a class you are actually creating a pretty complex wrapper around a dictionary - so, if anything, you are adding more overhead than by using a simple dictionary. An overhead which, by the way, is meaningless in any case. If you are working on performance critical applications, use C or something.
19.6k17 gold badges130 silver badges188 bronze badges
answered Aug 30, 2008 at 15:20
Vicent MartiVicent Marti
7,1036 gold badges30 silver badges33 bronze badges
I would also like to add a solution that uses slots:
Definitely check the documentation for slots but a quick explanation of slots is that it is python's way of saying: "If you can lock these attributes and only these attributes into the class such that you commit that you will not add any new attributes once the class is instantiated (yes you can add new attributes to a class instance, see example below) then I will do away with the large memory allocation that allows for adding new attributes to a class instance and use just what I need for these slotted attributes".
Example of adding attributes to class instance (thus not using slots):
Example of trying to add attributes to class instance where slots was used:
Output: AttributeError: 'Point' object has no attribute 'z'
This can effectively works as a struct and uses less memory than a class (like a struct would, although I have not researched exactly how much). It is recommended to use slots if you will be creating a large amount of instances of the object and do not need to add attributes. A point object is a good example of this as it is likely that one may instantiate many points to describe a dataset.
answered Apr 12, 2018 at 6:17
Oamar KanjiOamar Kanji
1,4544 gold badges19 silver badges34 bronze badges
You can subclass the C structure that is available in the standard library. The ctypes module provides a Structure class. The example from the docs:
answered Jun 25, 2015 at 23:50
Ella RoseElla Rose
4967 silver badges15 bronze badges
You can also pass the init parameters to the instance variables by position
answered Aug 30, 2008 at 15:53
24.8k10 gold badges45 silver badges59 bronze badges
Whenever I need an "instant data object that also behaves like a dictionary" (I don't think of C structs!), I think of this cute hack:
Now you can just say:
Perfectly handy for those times when you need a "data bag that's NOT a class", and for when namedtuples are incomprehensible...
answered Sep 13, 2013 at 17:40
5,5103 gold badges29 silver badges46 bronze badges
Some the answers here are massively elaborate. The simplest option I've found is (from: http://norvig.com/python-iaq.html):
edit: Sorry didn't see this example already further down.
answered Aug 5, 2017 at 0:39
3055 silver badges12 bronze badges
You access C-Style struct in python in following way.
if you just want use object of cstruct
if you want to create an array of objects of cstruct
Note: instead of 'cstruct' name, please use your struct name instead of var_i, var_f, var_str, please define your structure's member variable.
34.8k28 gold badges150 silver badges258 bronze badges
answered Nov 9, 2014 at 7:37
Sujal ShethSujal Sheth
3744 silver badges10 bronze badges
This might be a bit late but I made a solution using Python Meta-Classes (decorator version below too).
My example has no error checking so it is easier to follow.
Here it is in action.
I posted it on reddit and /u/matchu posted a decorator version which is cleaner. I'd encourage you to use it unless you want to expand the metaclass version.
answered Mar 23, 2015 at 14:32
792 silver badges5 bronze badges
I wrote a decorator which you can use on any method to make it so that all of the arguments passed in, or any defaults, are assigned to the instance.
A quick demonstration. Note that I use a positional argument
Note that my decorator should work with any method, not just
answered Sep 8, 2015 at 2:38
19.6k17 gold badges130 silver badges188 bronze badges
I don't see this answer here, so I figure I'll add it since I'm leaning Python right now and just discovered it. The Python tutorial (Python 2 in this case) gives the following simple and effective example:
That is, an empty class object is created, then instantiated, and the fields are added dynamically.
The up-side to this is its really simple. The downside is it isn't particularly self-documenting (the intended members aren't listed anywhere in the class "definition"), and unset fields can cause problems when accessed. Those two problems can be solved by:
Now at a glance you can at least see what fields the program will be expecting.
Both are prone to typos,
answered Nov 8, 2016 at 14:06
Jason CJason C
36.6k14 gold badges116 silver badges166 bronze badges
Here is a solution which uses a class (never instantiated) to hold data. I like that this way involves very little typing and does not require any additional packages etc.
You can add more fields later, as needed:
To get the values, the fields are accessed as usual:
answered Apr 9, 2019 at 11:10
3,4932 gold badges37 silver badges47 bronze badges
Personally, I like this variant too. It extends @dF's answer.
It supports two modes of initialization (that can be blended):
Also, it prints nicer:
answered Nov 6, 2017 at 15:38
7,1904 gold badges44 silver badges77 bronze badges
There is a python package exactly for this purpose. see cstruct2py
First we need to generate the pythonic structs:
Now we can import all names from the C code:
We can also do that directly:
Using types and defines from the C code
The output will be:
answered Dec 11, 2018 at 9:34
Here is a quick and dirty trick:
How does it works? It just re-use the builtin class
The good points are that you do not need to import or define anything first, that "Warning" is a short name, and that it also makes clear you are doing something dirty which should not be used elsewhere than a small script of yours.
By the way, I tried to find something even simpler like
answered Sep 26, 2019 at 13:56
5,3382 gold badges25 silver badges24 bronze badges
NamedTuple is comfortable. but there no one shares the performance and storage.
You can review this link(Usage of
slots) to get more
answered Jun 5, 2020 at 10:05
4,4242 gold badges27 silver badges36 bronze badges
https://stackoverflow.com/a/32448434/159695 does not work in Python3.
https://stackoverflow.com/a/35993/159695 works in Python3.
And I extends it to add default values.
answered Oct 30, 2017 at 13:40
1,7521 gold badge15 silver badges25 bronze badges
The following solution to a struct is inspired by the namedtuple implementation and some of the previous answers. However, unlike the namedtuple it is mutable, in it's values, but like the c-style struct immutable in the names/attributes, which a normal class or dict isn't.
answered Mar 29, 2018 at 16:25
If you don't have a 3.7 for @dataclass and need mutability, the following code might work for you. It's quite self-documenting and IDE-friendly (auto-complete), prevents writing things twice, is easily extendable and it is very simple to test that all instance variables are completely initialized:
answered Jan 28, 2019 at 11:27
1,6742 gold badges21 silver badges30 bronze badges
The best way I found to do this was to use a custom dictionary class as explained in this post: https://stackoverflow.com/a/14620633/8484485
If iPython autocompletion support is needed, simply define the dir() function like this:
You then define your pseudo struct like so: (this one is nested)
You can then access the values inside my_struct like this:
19.6k17 gold badges92 silver badges176 bronze badges
answered May 7, 2020 at 14:23
3262 silver badges5 bronze badges
I think Python structure dictionary is suitable for this requirement.
answered Jul 8, 2017 at 19:17
Why struct is used in Python?
The module struct is used to convert the native data types of Python into string of bytes and vice versa. We don't have to install it. It's a built-in module available in Python3. The struct module is related to the C languages.
How do you read a structure in Python?
Reading binary data as a numpy array:.
np. frombuffer(bytes_data, dtype=...) : Interpret the given binary data (e.g. a python bytes instance) as a numpy array of the given dtype. ... .
np. fromfile(filename, dtype=...) : Read binary data from filename ..