Iterable Ctypes Struct

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Feb 11 22:17:37 EST 2009


En Thu, 12 Feb 2009 00:02:12 -0200, <mark.seagoe at gmail.com> escribió:
> On Feb 11, 5:51 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>> On Wed, 11 Feb 2009 17:33:23 -0800, mark.seagoe wrote:

>> > Not sure what generic attribute container is.  I am reading in from >  
>> xml file all reg names for a chip.
>>
>> Are you using instances of that class to interface C code or to read/
>> write data intended to be read or written by a C program?  If not then
>> `ctypes` might be the wrong tool.
>
> It's accessing through USB so I'm also interfacing to Win32 drivers.
> But at this higher level, since I'm somewhat new to Python so I'm not
> aware of other classes which exist to allow accessing in the format
> desired (without quotes and using dot notation):
> classname.elementname1, instead of something like classname
> ["elementname1"].  It's just cosmetic, but I'd prefer the dot notation
> without quotes for the end user experience of script writing later.
> Is there something besides ctypes.Structure that would do that?

You don't need *anything* special to add attributes to an object in  
Python. Even an empty class is enough:

py> class Struct(object):
...   pass # an empty class
...
py> s = Struct()
py> s.x = 10
py> s.y = 20
py> print s.x, s.y
10 20
py>

But since this thread started asking how to iterate over the attributes,  
let's use a named tuple:

py> from collections import namedtuple
py> StructWithNames = namedtuple("StructWithNames", "x,y,z")
py> s = StructWithNames(10, 20, 30)
py> s.z
30
py> s
StructWithNames(x=10, y=20, z=30)
py> list(s)
[10, 20, 30]
py> for item in s: print item
...
10
20
30
py> s._fields
('x', 'y', 'z')

-- 
Gabriel Genellina




More information about the Python-list mailing list