[C++-sig] convertibility and "Pythonicity"

Leonardo Rochael Almeida leo at hiper.com.br
Thu Sep 12 23:09:11 CEST 2002

I just found out that some smtp server decided not to forward the
message below, which I sent on August 25th.

On Sat, 2002-08-24 at 10:14, David Abrahams wrote:
> [Is "Pythonicity" the right word?]

I don't know, but I like it :-)

> I'm interested in getting some qualitative feedback about something I'm
> doing in Boost.Python. The questions are,
>     1. How well does this behavior match up with what Python users have
> probably come to expect?
>     2. (related, I hope!) How close is it to the intended design of Python?
> When wrapping a C++ function that expects a float argument, I thought it
> would be bizarre if people couldn't pass a Python int. Well, Python ints
> have a lovely __float__ function which can be used to convert them to
> floats. Following that idea to its "logical" conclusion led me to where I
> am today: when matching a formal argument corresponding to one of the
> built-in Python types, first use the corresponding conversion slot.
> That could lead to some surprising behaviors:
>     char index(const char* s, int n); // wrapped using Boost.Python
>     >>> index('foobar', 2)    # ok
>     'o'
>     >>> index(3.14, 1.2)      # Wierd (floats have __str__)
>     '.'
>     >>> index([1, 3, 5], 0.0) # Super wierd (everything has __str__)
>     '['
> So I went back and tried some "obvious" test in Python 2.2.1:
>     >>> 'foobar'[3.0]
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     TypeError: sequence index must be integer
> Well, I had expected this to work, so I'm beginning to re-think my "liberal
> conversion" policy. It seems like Python itself isn't using these slots to
> do "implicit conversion". But then:
>     >>> 'foobar'[3L]
>     'b'

This fails in Python 1.5, works in 2.x

> [The int/long unification I've heard about hasn't happened yet, has it?]

More information about the Cplusplus-sig mailing list