473,587 Members | 2,466 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to set docstrings for extensions supporting PyNumberMethods ?

Hello,

I am writing a python extension (compiled C code) that defines an
extension type with PyNumberMethods . Everything works swimmingly,
except I can't deduce a clean way to set the docstring for tp_*
methods. That is, I always have

type.__long__._ _doc__ == 'x.__long__() <==long(x)'

which a quick glance at the Python 2.5 source shows is the default.

I have found that I can use PyObject_GetAtt r and PyWrapperDescrO bject
and set the descriptor objects d_base->doc to a char pointer... but I
can't tell if this is safe. Or the right way to do it.

If I'm on the wrong list, please let me know!
Thanks,
Nick Alexander

Mar 3 '07 #1
2 1657
Nick Alexander wrote:
Hello,

I am writing a python extension (compiled C code) that defines an
extension type with PyNumberMethods . Everything works swimmingly,
except I can't deduce a clean way to set the docstring for tp_*
methods. That is, I always have

type.__long__._ _doc__ == 'x.__long__() <==long(x)'

which a quick glance at the Python 2.5 source shows is the default.

I have found that I can use PyObject_GetAtt r and PyWrapperDescrO bject
and set the descriptor objects d_base->doc to a char pointer... but I
can't tell if this is safe. Or the right way to do it.

If I'm on the wrong list, please let me know!
Thanks,
Nick Alexander
I think that the right way is to add the methods to the tp_methods
slot and use METH_COEXIST in the PyMethodDef flags field. Example:

/* start of silly module */
#include "Python.h"

typedef struct {
PyObject_HEAD
double value;
} SillyNumber_Obj ect;

/* Forward declarations */
static PyTypeObject SillyNumber_Typ e;

#define SillyNumber_Che ck(op) PyObject_TypeCh eck(op,
&SillyNumber_Ty pe)

static PyObject *
new_SillyNumber (PyTypeObject *type, double value)
{
PyObject *self;

self = type->tp_alloc(typ e, 0);
if (self == NULL)
return NULL;

((SillyNumber_O bject *)self)->value = value;
return self;
}

static PyObject *
SillyNumber_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
double value = 0.0;
static char *kwlist[] = {"value", 0};

if (!PyArg_ParseTu pleAndKeywords( args, kwds, "|d:SillyNumber ",
kwlist, &value))
return NULL;

return new_SillyNumber (type, value);
}

static PyObject *
SillyNumber_add (PyObject *left, PyObject *right)
{
double sum;

if (!SillyNumber_C heck(left) || !SillyNumber_Ch eck(right)) {
Py_INCREF(Py_No tImplemented);
return Py_NotImplement ed;
}

sum = (((SillyNumber_ Object *)left)->value +
((SillyNumber_O bject *)right)->value);

return new_SillyNumber (&SillyNumber_T ype, sum);
}

static PyObject *
SillyNumber_rad d(PyObject *right, PyObject *left)
{
return SillyNumber_add (left, right);
}

static PyNumberMethods SillyNumber_as_ number = {
SillyNumber_add , /* nb_add */
0, /* nb_subtract */
0, /* nb_multiply */
0, /* nb_divide */
0, /* nb_remainder */
0, /* nb_divmod */
0, /* nb_power */
0, /* nb_negative */
0, /* nb_positive */
0, /* nb_absolute */
0, /* nb_nonzero */
};

static PyMethodDef SillyNumber_met hods[] = {
{"__add__", SillyNumber_add , METH_O | METH_COEXIST,
"Add two SillyNumbers."} ,
{"__radd__", SillyNumber_rad d, METH_O | METH_COEXIST,
"Same as __add__."},
{NULL, NULL, 0, NULL}
};

static PyTypeObject SillyNumber_Typ e = {
PyObject_HEAD_I NIT(NULL)
0, /* ob_size */
"silly.SillyNum ber", /* tp_name */
sizeof(SillyNum ber_Object), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
&SillyNumber_as _number, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFA ULT | /* tp_flags */
Py_TPFLAGS_CHEC KTYPES | /* PyNumberMethods do their own
coercion */
Py_TPFLAGS_BASE TYPE, /* SillyNumber_Typ e allows subclassing
*/
"Silly float numbers", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffs et */
0, /* tp_iter */
0, /* tp_iternext */
SillyNumber_met hods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
SillyNumber_new , /* tp_new */
0, /* tp_free */
};

static PyMethodDef silly_methods[] = {
{NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initsilly(void)
{
PyObject *module;

module = Py_InitModule3( "silly", silly_methods,
"silly floating number type");
if (module == NULL)
return;

if (PyType_Ready(& SillyNumber_Typ e) < 0)
return;

Py_INCREF(&Sill yNumber_Type);
PyModule_AddObj ect(module, "SillyNumbe r", (PyObject *)
&SillyNumber_Ty pe);
}

/* end of silly module */
Results from the interactive session:
>>import silly
print silly.SillyNumb er.__add__.__do c__
Add two SillyNumbers.
>>print silly.SillyNumb er.__radd__.__d oc__
Same as __add__.
>>n1 = silly.SillyNumb er(3)
n2 = silly.SillyNumb er(3.14)
type(n1 + n2) is silly.SillyNumb er
True

HTH,
Ziga

Mar 4 '07 #2
On Mar 4, 12:14 am, "Ziga Seilnacht" <ziga.seilna... @gmail.comwrote :
NickAlexanderwr ote:
Hello,
I am writing a python extension (compiled C code) that defines an
extension type with PyNumberMethods . Everything works swimmingly,
except I can't deduce a clean way to set the docstring for tp_*
methods. That is, I always have
type.__long__._ _doc__ == 'x.__long__() <==long(x)'
which a quick glance at the Python 2.5 source shows is the default.
I have found that I can use PyObject_GetAtt r and PyWrapperDescrO bject
and set the descriptor objects d_base->doc to a char pointer... but I
can't tell if this is safe. Or the right way to do it.
If I'm on the wrong list, please let me know!
Thanks,
NickAlexander

I think that the right way is to add the methods to the tp_methods
slot and use METH_COEXIST in the PyMethodDef flags field. Example:
Ziga, thanks for an extremely helpful reply. I'll experiment and post
again if there are issues.

Cheers!
Nick

Mar 5 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3381
by: Sridhar R | last post by:
When writing a python library, we can use docstrings for methods and functions that are part of API. But what about comments for non-API objects or python application code? For applications, docstrings are not really much useful. Instead language comments are prefered for them. Language comments (starting with #) are usually considered...
0
1248
by: Craig Ringer | last post by:
Hi folks I'm currently working on a fairly well internationalised app that embeds a Python intepreter. I'd like to make the docstrings translatable, but am running into the issue that the translation function returns unicode data. Does anybody here know what encoding docstrings in PyMethodDef are interpreted as? Is there any sane way to...
2
1830
by: Steven Bethard | last post by:
I have two classes that implement the same interface, e.g. something like: class C(object): def foo(self): """Foo things""" ... def bar(self): """Bar things""" ... def baz(self):
0
1109
by: Pedro Werneck | last post by:
Hi list I'm trying to implement a new type in a C extension and it must support some binary operators, like &, |, ^, << and >>. With &, | and ^, the method must receive another object of the same type, perform the operation with an attribute of both, create a new object with the result as the attribute and return it. Everything works...
6
3051
by: Kamilche | last post by:
I have a large project that is getting complex, and I would like to print the docstrings without importing the modules. The only Python utility I could find references is apparently defunct and hasn't been updated in 4 years. I don't care how spartan the output is - it could look exactly like python's internal docstrings, for all I care. ...
0
1090
by: Edward Loper | last post by:
Epydoc 3 supports extracting information about Python modules by parsing. As a result, it can extract "docstrings" for variables. There are several possible ways these docstrings could be expressed in the Python source file, and I wanted to get some feedback on which ways people prefer. It's my hope that some consensus can be reached on...
12
3125
by: jelle | last post by:
That's basically the idea... Often i find myself annotating what variables actually stand for, so to refer back to the code in half a year or so. # check if ID's or coords self.pointIDs = ptIDs self.coords = # map ids/coords and coords/ids self.pointID_2_Coord, self.coord_2_pointID = {}, {}
1
1653
bartonc
by: bartonc | last post by:
You will be rewarded sooner than you think when you use docstrings to document your classes and functions. Whether you ever intend to publish your work or not, docstrings will help you in several ways. First, let me show you the syntax: def Add(a, b): """Return the sum of two addable types. This is a very simple example of docstring...
0
982
by: tjhnson | last post by:
The topic of docstrings for variables has come up many times before. In fact, a PEP was proposed and rejected on this very topic. http://www.python.org/dev/peps/pep-0224/ When creating classes, I like using properties...and I like even more that these properties have docstrings. This allows one to interactively explore the API and...
0
7920
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8347
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7973
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6626
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5718
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3844
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1454
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1189
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.