I tried to add some diagnostics to a nested ctypes structure but failed to do so and would like to know the reason. A bare-bones example for what works as expected:
import ctypes
class FirstStruct(ctypes.Structure):
_fields_ = [('ch', ctypes.c_ubyte)]
f = FirstStruct()
print type(f)
print hasattr(f, 'helper')
f.helper = 'xyz'
print hasattr(f, 'helper')
These lines print what I expected:
<class '__main__.FirstStruct'>
False
True
But when I use this in another Structure it fails:
class SecondStruct(ctypes.Structure):
_fields_ = [('first', FirstStruct)]
s = SecondStruct()
print type(s.first)
print hasattr(s.first, 'helper')
s.first.helper = 'xyz'
print hasattr(s.first, 'helper')
The above results in
<class '__main__.FirstStruct'>
False
False
Can someone please explain me the difference? (I was running it on Python 2.7.8. Mind you, I don't want to change the structure itself, but wanted to add an extra variable outside the ctypes structure.)
EDIT:
Here's a more direct example:
import ctypes
class FirstStruct(ctypes.Structure):
_fields_ = [('ch', ctypes.c_ubyte)]
class SecondStruct(ctypes.Structure):
_fields_ = [('first', FirstStruct)]
f = FirstStruct()
s = SecondStruct()
f.helper = 'aaa'
s.first.helper = 'bbb'
s.first.ch = 0
t = s.first
t.helper = 'ccc'
t.ch = 12
print f.helper # aaa
print t.ch # 12
print s.first.ch # 12
print t.helper # ccc
print s.first.helper # AttributeError: 'FirstStruct' object has no attribute 'helper'
The questions are: why isn't s.first
and t
equivalent, and why doesn't s.first.helper
trigger a warning if I can't set it after all?