[Python-porting] porting builtin file type to python3

John Machin sjmachin at lexicon.net
Tue Jan 20 01:38:16 CET 2009


On 20/01/2009 10:50 AM, Bernhard Leiner wrote:
> 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?
> 

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


More information about the Python-porting mailing list