[capi-sig] String to number conversion

M.-A. Lemburg mal at egenix.com
Wed May 7 18:40:51 CEST 2008

On 2008-05-07 18:28, Rasmus Andersson wrote:
> On 7 maj 2008, at 17.46, M.-A. Lemburg wrote:
>> On 2008-05-07 17:27, Hrvoje Niksic wrote:
>>> I miss a function able to convert the string representation of a
>>> Python primitive number (int, long, float, complex) to an actual
>>> number, basically the reverse of repr for numbers.
>>> <snip>
>>> Would anyone else find this kind of function useful?
>> Yes.
>> Perhaps as PyNumber_FromString() ?!
> I rarely wrap primitives in objects, as this increases both memory 
> usage, complexity and overhead.  (However, sometimes you _might_ need 
> to, but I can't come up with a scenario)
> So, in most cases this would probably happen:
> PyObject *num = PyNumber_FromString(num_s);
> if(!PyLong_Check(num)) {
>   // Error...
> }
> else {
>   self->event_id = PyLong_AsLongLong(num);
> }

Not really. The point of the PyNumber_* API is to work on numbers
without actually caring or knowing the specific number types

You'd only do the final conversion to a specific number type
at the very end of the calculation using e.g. PyNumber_Int().

In some cases, not even that, since all you're interested in
is converting some object to a number object and then passing
that to e.g. marshal.

> And you lose, because this would be simpler:
> self->event_id = strtoll(PyString_AsString(num_s), (char *)NULL, 10);
> if(errno == EINVAL) {
>   // Error...
> }
> Meaning, you rarely need to take input which can be any kind of number 
> manifested as a string and return it as any number manifested as a 
> native number. (The examples above indicate the output type is known 
> (signed 64bit integer))
> Could you maybe give a real-world scenario where this would be needed? 
> Where neither the input not the output number type is known.

Parsing numeric data and converting it to some other format.

Marc-Andre Lemburg

Professional Python Services directly from the Source  (#1, May 07 2008)
 >>> Python/Zope Consulting and Support ...        http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::

    eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
     D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
            Registered at Amtsgericht Duesseldorf: HRB 46611

More information about the capi-sig mailing list