1

The docs for Python C API describes the pattern of defining a new type:

typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
} Noddy;
...

Then methods such as init could be added.

My question is - what is the point to define custom fields in a struct, why not define them in init, just like in Python, using PyObject_SetAttr function calls on self?

Gill Bates
  • 14,330
  • 23
  • 70
  • 138
  • I don't think this is a vbalid question, it's like what is the point of having stereo in a car? So the answer is extermely simple, **you can use it if you need it**, and almost surely at some point you will need it. – Iharob Al Asimi Apr 09 '15 at 12:06
  • @inarob More like "What is the point to have stereo in a car welded to the car body?" – Gill Bates Apr 09 '15 at 12:11
  • No, it's not like that, because you do need this kind of structure I have used them myself and it allows a programmer to write a python object using c, and you must know that the performance difference is HUGE. – Iharob Al Asimi Apr 09 '15 at 12:13
  • @inarob So the main reason is a performance? – Gill Bates Apr 09 '15 at 12:14
  • Not necessarily, you can extend python with c, so if you need it you can do it, sometimes you do, for example you have a c library and you want to be able to use it from python, sometimes you write a c library just for performance issues and then you use it from python. – Iharob Al Asimi Apr 09 '15 at 12:18

1 Answers1

3
  1. Struct member access is far more efficient than dict lookups.
  2. Struct member access is far more convenient to do in C. It's much easier to do thing->foo than PyObject_GetAttrString(thing, "foo").
  3. Using struct members allows you to store data that isn't of a Python type. This allows you to do things that can't be implemented in terms of Python types, or that would be much less efficient in terms of Python types.
  4. Using struct members prevents every object from needing its own dict. The most important result of this is that a dict doesn't have to have an infinite descending chain of dicts, but it also improves space efficiency.
  5. This API existed before Python-level class statements and the way those statements do things.
user2357112
  • 260,549
  • 28
  • 431
  • 505