28

I am going to define a structure and pass it into a function:

In C:

struct stru {
int a;
int b;
};

s = new stru()
s->a = 10;

func_a(s);

How this can be done in Python?

Bin Chen
  • 61,507
  • 53
  • 142
  • 183

4 Answers4

37

Unless there's something special about your situation that you're not telling us, just use something like this:

class stru:
    def __init__(self):
        self.a = 0
        self.b = 0

s = stru()
s.a = 10

func_a(s)
Nathan Davis
  • 5,636
  • 27
  • 39
  • Does this pass by reference or by value? I don't want to pass a Vector3 or similar structure, change something about it in a function, and have it change the original. – Aaron Franke Mar 07 '19 at 08:12
  • @AaronFranke Objects are passed by reference in python, so `s` or any other `stru` would be passed by reference. But you can always `copy` an object, or use an immutable `namedtuple`, if you want to avoid unexpected changes. – Nathan Davis Mar 09 '19 at 22:06
13

use named tuples if you are ok with an immutable type.

import collections

struct = collections.namedtuple('struct', 'a b')

s = struct(1, 2)

Otherwise, just define a class if you want to be able to make more than one.

A dictionary is another canonical solution.

If you want, you can use this function to create mutable classes with the same syntax as namedtuple

def Struct(name, fields):
    fields = fields.split()
     def init(self, *values):
         for field, value in zip(fields, values):
             self.__dict__[field] = value
     cls = type(name, (object,), {'__init__': init})
     return cls

you might want to add a __repr__ method for completeness. call it like s = Struct('s', 'a b'). s is then a class that you can instantiate like a = s(1, 2). There's a lot of room for improvement but if you find yourself doing this sort of stuff alot, it would pay for itself.

aaronasterling
  • 68,820
  • 20
  • 127
  • 125
8

Sorry to answer the question 5 days later, but I think this warrants telling.

Use the ctypes module like so:

from ctypes import *

class stru(Structure):
    _fields_ = [
        ("a", c_int),
        ("b", c_int),
    ]

When you need to do something C-like (i.e. C datatypes or even use C DLLs), ctypes is the module. Also, it comes standard

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
2

Use classes and code Python thinking in Python, avoid to just write the same thing but in another syntax.

If you need the struct by how it's stored in memory, try module struct

Rafael Sierra
  • 459
  • 1
  • 4
  • 14
  • Python's philosophy states that Python is a multi-paradigm programming language. Object-orientation is not a better way to do it in Python. – jacekmigacz Apr 01 '18 at 10:31