PyArg_ParseTupleAndKeywords in Python3.1

Case Vanhorsen casevh at gmail.com
Fri Dec 18 11:24:04 EST 2009


On Fri, Dec 18, 2009 at 7:57 AM, Emeka <emekamicro at gmail.com> wrote:
> Case,
> Thanks so much! However, I am still confused. This is what I understood;
> foo (a = "a", b = "b") so function , foo,  has default values which are "a"
> and "b". pointer kwlist[] is a way of specifying default values .
> Regards,
> Emeka
kwlist just specifies the names. The default values are specified by
"int a=65, b=66;". 65 is equivalent to 'A' and 66 is equivalent to
'B'.

casevh
>
> On Fri, Dec 18, 2009 at 3:02 PM, Case Vanhorsen <casevh at gmail.com> wrote:
>>
>> On Fri, Dec 18, 2009 at 2:26 AM, Emeka <emekamicro at gmail.com> wrote:
>> >    char *kwlist[] = {"a", "b", NULL};
>> >    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
>> > &b))
>> > I am yet to understand what pointer kwlist[] does and why it is needed?
>> > Regards,
>> > Emeka
>>
>> foo is designed to accept two arguments that can be specified by
>> either position or name. kwlist contains the legal keyword names. In
>> this example, the legal keywords are 'a' and 'b'. That they match the
>> names of the C variables is just a lucky coincidence. If you want to
>> change the keyword names to 'foo' and 'bar', you would just use char
>> *kwlist[]={"foo", "bar", NULL}.
>>
>> casevh
>> >
>> > On Fri, Dec 18, 2009 at 8:17 AM, casevh <casevh at gmail.com> wrote:
>> >>
>> >> On Dec 17, 11:14 am, Joachim Dahl <dahl.joac... at gmail.com> wrote:
>> >> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's
>> >> > a
>> >> > related bug:
>> >> >
>> >> > >>> foo(b='b')
>> >> >
>> >> > will set the value of a in the extension module to zero, thus
>> >> > clearing
>> >> > whatever
>> >> > default value it may have had.  In other words, the optional
>> >> > character
>> >> > arguments
>> >> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().
>> >>
>> >> The following code seems to work fine for me:
>> >>
>> >> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
>> >> {
>> >>    int a=65, b=66;
>> >>    char *kwlist[] = {"a", "b", NULL};
>> >>    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
>> >> &b))
>> >>        return NULL;
>> >>    return Py_BuildValue("(CC)", a, b);
>> >> }
>> >>
>> >> The default values seem to remain as 'A' and 'B'.
>> >>
>> >> >>> foo()
>> >> ('A', 'B')
>> >> >>> foo(b='b')
>> >> ('A', 'b')
>> >> >>> foo()
>> >> ('A', 'B')
>> >> >>> foo('a')
>> >> ('a', 'B')
>> >> >>> foo('a', b='b')
>> >> ('a', 'b')
>> >> >>> foo()
>> >> ('A', 'B')
>> >> >>>
>> >>
>> >> casevh
>> >> --
>> >> http://mail.python.org/mailman/listinfo/python-list
>> >
>> >
>
>



More information about the Python-list mailing list