Lisandro Dalcin, 28.06.2010 22:52:
> While porting petsc4py to work in Python 3, I noticed that __div__
> special method is ignored. Should __truediv__ have __div__ as a
> fallback ?

-1, they're different things:

   >>> class test(object):
   ...   def __div__(a,b): return b
   ...
   >>> t = test()
   >>> t / 2
   2
   >>> t // 2
   Traceback (most recent call last):
   TypeError: unsupported operand type(s) for //: 'test' and 'int'

And I can't find a fixer in 2to3 either.

What about a warning instead when __div__ is defined but __truediv__ is not?


> PS: the bytes/unicode thing was again a major pain. I had to insert a
> call to a helper function at EVERY point the str ->  bytes ->  char*
> conversion was needed. Stefan, any chance you have implemented some
> sugar I'm not aware of?

No. You need a helper function here, as you need to check if the str input 
is valid input for your code. You didn't say what kind of input it can 
accept, but assuming it's a subset of ASCII, you will have to make sure 
it's really a suitable string, both in Py2 and Py3. Decoding a unicode 
string here is not substantially more work, neither in Py2 nor in Py3 
(assuming that you accept unicode strings in Py2 as well, which I hope you do).

Encoding is really just a small part of the work, but remember that the 
problem here is Py2, not Py3. Input checking is much easier in Py3, where 
you only need to call .encode(target_encoding) on the input string, and 
bytes input as well as incompatible unicode input will raise an exception 
for free. Then all you have to do is check the data for invalid bytes 
afterwards, such as NULL bytes or other constrains.

In Py2, you have to check the type of the string, then either encode it 
(unicode input) or check the byte data for incompatible input data, and 
only then can you take the result of either of the two and check it for 
invalid bytes. That's a lot more complicated.

However, in both cases, a helper function is the right way to do it, as it 
builds a single point of truth that holds your input constrains.

Stefan
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to