Przemyslaw Zych
Przemyslaw Zych

Reputation: 2060

Python: Deriving from ctypes POINTER and "TypeError: Cannot create instance: has no _type_"

I'm trying to force Python 2.7 to print a formatted string for a ctypes POINTER(<type>). I figured I'll write a class that inherits from POINTER and overload __str__. Unfortunately running this piece of code:

from ctypes import *

pc_int = POINTER(c_int)
class PInt(pc_int):
    def __str__(self):
        return "Very nice formatting ", self.contents

print pc_int(c_int(5))
print PInt(c_int(5))

fails with such exception

$ python playground.py
<__main__.LP_c_int object at 0x7f67fbedfb00>
Traceback (most recent call last):
  File "playground.py", line 9, in <module>
    print PInt(c_int(5))
TypeError: Cannot create instance: has no _type_

Does anyone know how to cleanly achieve the anticipated effect or what this exception means?

There's only 1 google search result for "TypeError: Cannot create instance: has no type" and it isn't that helpful.

Thanks!

Upvotes: 1

Views: 958

Answers (1)

nneonneo
nneonneo

Reputation: 179402

The problem is that the ctypes metaclass used to implement POINTER and related classes looks directly in the class dictionary for special fields like _type_, and therefore can't handle inherited special fields.

The fix is simple:

pc_int = POINTER(c_int)
class PInt(pc_int):
    _type_ = c_int # not pc_int
    ...

Upvotes: 3

Related Questions