1

I'm working on a Python extension module written in C++.

According to the Python documentation the module method table should be written like this:

static PyMethodDef SpamMethods[] = {
    ...
    {"system",  spam_system, METH_VARARGS,
    "Execute a shell command."},
    ...
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

But I see that some developers write the sentinel like this:

static PyMethodDef SpamMethods[] = {
    ...
    {"system",  spam_system, METH_VARARGS,
    "Execute a shell command."},
    ...
    {}                          /* Sentinel */
};

My question is the following is there a risk to use the shortened version?

Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
  • There does not appear to be any risk. – Captain Obvlious May 20 '15 at 20:00
  • According to this post, there is no risk: http://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default Everything gets initialised to zero by default. – RomanK May 20 '15 at 20:14
  • [psmears](http://stackoverflow.com/users/333698/psmears) made a very interesting point about there not being a problem even if such code is compiled under C. – Ami Tavory May 20 '15 at 20:31

1 Answers1

2

A pod class initialized with {} has fields not explicitly set zeroed.

If PyMethodDef is pod (plain old data), as I suspect, {NULL, NULL, 0, NULL} will generate the same data as {}.

This is true in both C and C++.

If the class PyMethodDef was a non-pod class in C++11, {NULL, NULL, 0, NULL} could do something different than {}, but I strongly doubt that is the case here.

The only concern I would have is if the library changed on me to make PyMethodDef a non-pod, and chose to make {} not zero the data at the same time. I would find that unlikely.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524