Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 555497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:49:14+00:00 2026-05-13T11:49:14+00:00

When creating a class in Python, I can simply make a def __len__(self): method

  • 0

When creating a class in Python, I can simply make a def __len__(self): method to make the len(InstanceOfMyClass) work, however I can’t find out how to do this with an extension class via the C-API.

I tried adding a __len__ method, but that appears to not work

{"__len__",(PyCFunction)&TestClass_GetLen,METH_NOARGS,""},

Python test code:

def test(my_instance):
    x = len(my_instance)#exception
    return x

TypeError: object of type 'test_module.test_class' has no len()

Code for TestClass

struct TestClass;
static int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds);
static void TestClass_Dealloc(TestClass *self);
static PyObject* TestClass_GetLen(TestClass *self);

struct TestClass
{
    PyObject_HEAD;
};
static PyMethodDef TestClass_methods[] =
{
    {"__len__",(PyCFunction)&TestClass_GetLen,METH_O,""},
    {NULL}
};
static PyTypeObject TestClass_type = {PyObject_HEAD_INIT(NULL)};
bool InitTestClass(PyObject *module)
{
    TestClass_type.tp_basicsize = sizeof(TestClass);
    TestClass_type.tp_name      = PY_MODULE_NAME".TestClass";
    TestClass_type.tp_doc       = "";
    TestClass_type.tp_flags     = Py_TPFLAGS_DEFAULT;
    TestClass_type.tp_methods   = TestClass_methods;
    TestClass_type.tp_new       = PyType_GenericNew;
    TestClass_type.tp_init      = (initproc)TestClass_Init;
    TestClass_type.tp_dealloc   = (destructor)TestClass_Dealloc;
    if(PyType_Ready(TestClass_type) < 0) return false;

    Py_INCREF(TestClass_type);
    PyModule_AddObject(module, "TestClass", (PyObject*)&TestClass_type);
    return true;
};
void TestClass_Dealloc(TestClass *self)
{
    Py_TYPE(self)->tp_free((PyObject*)self);
}
int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds)
{
    return 0;
}
PyObject* TestClass_GetLen(TestClass *self)
{
    return PyLong_FromLong(55);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T11:49:15+00:00Added an answer on May 13, 2026 at 11:49 am

    As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example:

    #include <Python.h>
    
    /**
     * C structure and methods definitions
     */
    
    typedef struct {
        PyObject_HEAD;
    } TestObject;
    
    static Py_ssize_t
    TestClass_len(TestObject* self) 
    {   
        return 55;
    }
    
    /**
     * Python definitions
     */
    
    static PySequenceMethods TestClass_sequence_methods = {
        TestClass_len,                  /* sq_length */
    };
    
    static PyTypeObject TestClass = {
        PyObject_HEAD_INIT(NULL)    
        0,                              /*ob_size*/
        "testmodule.TestClass",         /*tp_name*/
        sizeof(TestObject),             /*tp_basicsize*/
    };
    
    /**
     * Module entry point
     */
    #ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */
    #define PyMODINIT_FUNC void
    #endif
    PyMODINIT_FUNC
    inittestmodule(void) 
    {
        PyObject* m;
    
        TestClass.tp_new = PyType_GenericNew;
        TestClass.tp_as_sequence = &TestClass_sequence_methods;
        TestClass.tp_flags = Py_TPFLAGS_DEFAULT;
    
        if (PyType_Ready(&TestClass) < 0)
            return;
    
        m = Py_InitModule3("testmodule", NULL, "");
    
        Py_INCREF(&TestClass);
        PyModule_AddObject(m, "TestClass", (PyObject *)&TestClass);
    }
    

    Another (more complicated and slower) way is to add a __len__ method to your class dynamically in the module’s init function with PyCFunction_New, PyMethod_New and PyObject_SetAttr. This would look more like the code you pasted, except that you defined __len__ in the C methods table, which doesn’t work.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 310k
  • Answers 311k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You need to do a join on the tables in… May 13, 2026 at 10:17 pm
  • Editorial Team
    Editorial Team added an answer If you want ActiveSync to appear in your Visual Studio… May 13, 2026 at 10:17 pm
  • Editorial Team
    Editorial Team added an answer Based on your comment, you're limited to what the third-party… May 13, 2026 at 10:17 pm

Related Questions

I have a code file from the boto framework pasted below, all of the
I have been trying to create a decorator that can be used with both
hopefully someone here can shed some light on my issue :D I've been creating
I'm running a for loop inside a function which is creating instances of a
I have this dictionary in my apps model file: TYPE_DICT = ( (1, Shopping

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.