0

I have a few custom types defined in C code.

When developing Python code based on these, I sometimes encounter an error, which is compounded when Python's own getfile() function (inside inspect.py) raises its own exception:

TypeError('{!r} is a built-in class'.format(object))

Because I'd like to see the underlying original error instead of the above, I'm wondering, if I can add the __module__ and the __file__ attributes to my own types. How would one do that?

The documentation seems to imply, attributes must be part of the object -- an obvious waste in the case like mine, when the values are exactly the same for all instances of the class -- how can I make them static?

If I try to implement type-specific attribute management, I suddenly lose access to the type's methods (because now they are treated as attributes).

Is it possible for such attributes to coexist with methods? How would I do that? My main target is Python-3.x...

Mikhail T.
  • 3,043
  • 3
  • 29
  • 46

1 Answers1

1

In the tp_name slot of your C-level type definition, write the fully-qualified name:

"your_module.YourClass"

The __module__ of the type object will be set based on tp_name. The __file__ attribute of the module should already be handled automatically.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thanks! This solves my particular problem. Still, I wonder, how would one have custom _static_ attributes without losing access to methods... – Mikhail T. Sep 05 '18 at 13:57
  • 1
    @MikhailT.: https://stackoverflow.com/questions/2374334/static-variables-in-python-c-api, but it's the wrong thing to do for `__module__`. – user2357112 Sep 05 '18 at 16:51