Python Forum
Adding C methods to a pure python class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding C methods to a pure python class
#1


Hi, I have a question on the C extension. Please guide me if it's not the right place.

I wanted to add C methods into a pure python class, but I couldn't find any documentation on that.
After hours of hacking the python source, I finally succeeded to do that.
I attached a POC code for Python 2.7.
Can anyone comment on whether this kind of hack - implementing only a part of a class in C,
instead of implementing the whole class in C - will be likely supported on future Python versions?


* python source

  class X(object):
    pass

  import x_ext
  X().test(1)

* C extension

  static PyObject *x_test(PyObject *self, PyObject *args)
  {
    puts("test");
    PyObject_Print(args, stdout, 0);
    puts("");
    Py_RETURN_NONE;
  }
  PyMODINIT_FUNC initx_ext(void)
  {
    Py_InitModule("x_ext", NULL);
    {
      PyObject *type = PyDict_GetItemString(PyEval_GetGlobals(), "X");
      static PyMethodDef test_def = {"test", (PyCFunction)x_test, METH_VARARGS, NULL};
      PyObject *descr = PyDescr_NewMethod((PyTypeObject *)type, &test_def);
      PyObject_SetAttrString(type, test_def.ml_name, descr);
      Py_DECREF(descr);
    }
  }
Reply
#2
This definitely looks like a hack to me, lol.  Anytime there's side effects with importing a package, that smells like a hack.  I think it would be better to just define functions as part of the module, then attach them after importing.  Something like this:
import x_ext

class X:
    def __init__(self):
        self.test = x_ext.test

X().test(1)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Class test : good way to split methods into several files paul18fr 4 508 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  Structuring a large class: privite vs public methods 6hearts 3 1,099 May-05-2023, 10:06 AM
Last Post: Gribouillis
  access share attributed among several class methods drSlump 0 1,077 Nov-18-2021, 03:02 PM
Last Post: drSlump
  a function common to methods of a class Skaperen 7 2,661 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Listing All Methods Of Associated With A Class JoeDainton123 3 2,382 May-10-2021, 01:46 AM
Last Post: deanhystad
  too many methods in class - redesign idea? Phaze90 3 2,521 Mar-05-2021, 09:01 PM
Last Post: deanhystad
  Special Methods in Class Nikhil 3 2,314 Mar-04-2021, 06:25 PM
Last Post: Nikhil
  adding user to a class Nickd12 3 2,196 Oct-15-2020, 03:55 AM
Last Post: deanhystad
  cant able to make methods interact with each other in the class jagasrik 2 1,819 Sep-16-2020, 06:52 PM
Last Post: deanhystad
  How to see python default methods from inside mariolucas75 3 2,450 Jun-14-2020, 11:41 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020