s-m-e
s-m-e

Reputation: 3711

Why does hasattr raise a ValueError although attribute exists?

I ran across something odd. See the following example:

>>> class demo(ctypes.Structure):
...     _fields_ = [('data', ctypes.POINTER(ctypes.c_int16))]

>>> b = demo()

>>> b.data
<__main__.LP_c_short object at 0x7f709c0550d0>

>>> hasattr(b.data, 'contents')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: NULL pointer access
NULL pointer access

>>> 'contents' in dir(b.data)
True

I guess the above behavior is intended, although I do not fully understand it. data is a field in a ctypes structure, defined as a pointer to an integer. It is uninitialized, i.e. a NULL pointer. It does have a contents attribute like one would expect (dir does list it), although accessing it would not make sense. I'd expect that hasattr also returns True, but instead it raises a ValueError. Why is that?

Upvotes: 1

Views: 245

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

hasattr is implemented by calling getattr and seeing whether an AttributeError is raised.

Since accessing the contents attribute of a ctypes pointer tries to dereference the pointer you are seeing what you are seeing.

Upvotes: 2

Related Questions