When creating ctypes.Structure classes dynamically, there's a gotcha.
_fields_ is final, but it takes a list that can be appended to. I'm not
sure this is a bug, but I would argue it is a lot more surprising than
it could be:
Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> class Foo(ctypes.Structure):
... _fields_ = [('dim', ctypes.c_int)]
...
>>> x = Foo()
>>> x.dim = 1
>>> x.dim = '123' # This is ok, and expected
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>>
>>>
>>> class Bar(ctypes.Structure):
... pass
...
>>> x._fields_ = []
>>> x._fields_.append(('dim', ctypes.c_int))
>>> x = Bar()
>>> x.dim = '123' # This, however, is strange
>>>
This was somewhat foreseen, since _fields_ is final:
>>> class Baz(ctypes.Structure):
... pass
...
>>> Baz._fields_ = []
>>> Baz._fields_ = [('dim', ctypes.c_int)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: _fields_ is final
Would it not make sense for _fields_ to require a tuple, so that it
cannot be mutated? I realize this is a big change. Currently, ctypes
accepts tuples as the input to _fields_. Maybe a warning should be
issued when a list is assigned to _fields_?
|