Discussion:
porting builtin file type to python3
Bernhard Leiner
2009-01-19 23:50:43 UTC
Permalink
Hi,

I have a custom file type that looks more or less like this:

class myfile(file):

def __init__(self, name, mode):
super(myfile, self).__init__(name, mode)
self.write('file header...\n')

And I'm pretty sure that porting this class to python3 will result in
something like:

import io

class myfile(io.FileIO):

def __init__(self, name, mode):
super(myfile, self).__init__(name, mode)
self.write('file header...\n')

The problem that I'm facing now is that the 2to3 script does not find
anything to convert. (I'm also surprised, that running the original
code with "python2.6 -3" does not result in a warning.)

What is the best way to alter my original script to keep it compatible
with python 2.x and get an equivalent python3 script after running
2to3?

thanks a lot,
bernhard
--
Bernhard Leiner http://bernh.net
John Machin
2009-01-20 00:38:16 UTC
Permalink
Post by Bernhard Leiner
Hi,
super(myfile, self).__init__(name, mode)
self.write('file header...\n')
And I'm pretty sure that porting this class to python3 will result in
import io
super(myfile, self).__init__(name, mode)
self.write('file header...\n')
The problem that I'm facing now is that the 2to3 script does not find
anything to convert. (I'm also surprised, that running the original
code with "python2.6 -3" does not result in a warning.)
What is the best way to alter my original script to keep it compatible
with python 2.x and get an equivalent python3 script after running
2to3?
2to3 and "python2.6 -3" can't handle everything. You'll need something
like the following, which seems to work with
2.5, 2.6, and 3.0 (win32 platform).
8<---
import sys
python_version = sys.version_info[:2]

if python_version >= (3, 0):
from io import FileIO as BUILTIN_FILE_TYPE
else:
BUILTIN_FILE_TYPE = file

class MyFile(BUILTIN_FILE_TYPE):

def __init__(self, name, mode):
super(MyFile, self).__init__(name, mode)
# maybe should test mode before writing :-)
self.write('file header...\n')

fname = "Bernhard%d%d.txt" % python_version
f = MyFile(fname, 'w')
f.write('foo bar zot\n')
f.close()
8<---

Cheers,
John
Benjamin Peterson
2009-01-20 01:14:21 UTC
Permalink
On Mon, Jan 19, 2009 at 5:50 PM, Bernhard Leiner
Post by Bernhard Leiner
Hi,
super(myfile, self).__init__(name, mode)
self.write('file header...\n')
And I'm pretty sure that porting this class to python3 will result in
import io
super(myfile, self).__init__(name, mode)
self.write('file header...\n')
2to3 would be quite happy to convert use of the file class to
io.FileIO if this was the right thing to do in 99.8% of all cases.
However, in 3.0, IO has been restructured quite a bit, and FileIO is
just a bare bones binary reading and writing class. Therefore you will
have to do something like John suggested.
--
Regards,
Benjamin
Loading...