tags:

views:

174

answers:

4

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?

+3  A: 

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
hi, you second example (object()) can't compile...
Bin Chen
Bin Chen. Correct. That keeps happening to me.
aaronasterling
+1  A: 

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 SDM Sierra
+3  A: 

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
I think you mean `self.a = 0`. this gets old quickly.
aaronasterling
Yes, you are right. I corrected the example.
Nathan Davis
A: 

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