<br><div class="gmail_quote">On Wed, Mar 2, 2011 at 10:58 PM, Gregory Ewing <span dir="ltr"><<a href="mailto:greg.ewing@canterbury.ac.nz">greg.ewing@canterbury.ac.nz</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
What is the recommended way to write code for 2.7 using<br>
maketrans() on text strings in such a way that it will<br>
convert correctly using 2to3?<br>
<br>
There seems to be two versions of maketrans in 3.x, one<br>
for text and one for bytes. Code that references<br>
string.maketrans ends up with the one for bytes, which<br>
is not what I want. But I can't write str.maketrans,<br>
because that doesn't exist in 2.x.<br>
<br>
So what am I supposed to do?<font color="#888888"><br></font></blockquote><div> </div><div>I've not tried maketrans, but I've been having some luck writing Python that works, unchanged (not even run through 2to3), on both CPython 2.x (2.5, 2.6, 2.7), CPython 3.x (3.1, 3.2) and pypy (1.4.1 which does Python 2.5 and a recent trunk that pretty much does Python 2.7).<br>
<br>For strings vs bytes, I've been finding that just using os.read and os.write helps; on 2.x they do str, on 3.x they do bytes.<br><br>You can usually then just pass things around as str or bytes, unchanged, depending on what your runtime prefers. If you need an ordinal, you can use isinstance and take the ord when you have a str of length 1 - otherwise you've already got an ordinal.<br>
<br>The other main sticky point for str vs bytes this way is sometimes I need a null string to express things nicely, but that can be done with the following in 3.x:<br><br><div style="margin-left: 40px;">''.encode('utf-8')<br>
</div><br>...without choking a 2.x parser (b'' blows up most, if not all, 2.x parsers), but it's probably best to wrap that up in a scope (module?) of its own rather than scattering it throughout your code.<br>
<br>Also, and this was a little surprising to me, if you build your modules with Cython, you may find that you conveniently get C extension modules for 2.x and 3.x from the same Cython code, with just a pair of recompiles (one from Cython to C, one from C to binary) for each CPython you need to support. And the performance benefit of Cython appears to be even greater on 3.x than it was on 2.x (at least in my minimal testing). There's a branch of Cython in testing now that does generators, BTW, which has been working well for me.<br>
<br></div></div>