[issue2680] gotcha: _fields_ is final but accepts lists

Carlos Scheidegger report at bugs.python.org
Thu Apr 24 18:29:58 CEST 2008


New submission from Carlos Scheidegger <cscheid at sci.utah.edu>:

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_?

----------
assignee: theller
components: ctypes
messages: 65728
nosy: cscheid, theller
severity: normal
status: open
title: gotcha: _fields_ is final but accepts lists
type: behavior
versions: Python 2.5

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue2680>
__________________________________


More information about the Python-bugs-list mailing list