[Spice-devel] [PATCH] Make spice_codegen.py work on both Python 2 and 3

Alexander Wauck awauck at codeweavers.com
Tue Mar 31 09:23:40 PDT 2015


On Tue, 31 Mar 2015 17:57:59 +0200
Christophe Fergeau <cfergeau at redhat.com> wrote:


> From a quick glance, the changes look sane to me (split patch would have
> been even more straightforward to review ;)

Duly noted.  I'll keep that in mind for the future.

> First time I hear about six.py, so I don't know about that :(

six.py is a collection of helpers for Python 2/3 compatibility.  It's generally
installable from the distribution's repositories, hence my ambivalence about
bundling it.  Bundling is easy (at least in this case), but I know Debian would
throw a fit over it.

> One comment below:
> 
> > diff --git a/python_modules/codegen.py b/python_modules/codegen.py
> > index 009cf95..4ff4c55 100644
> > --- a/python_modules/codegen.py
> > +++ b/python_modules/codegen.py
> > @@ -119,21 +120,24 @@ class CodeWriter:
> >          return writer
> >  
> >      def write(self, s):
> > -        # Ensure its a string
> > -        s = str(s)
> > +        # Ensure its a unicode string
> > +        if six.PY2:
> > +            s = unicode(s)
> > +        else:
> > +            s = str(s)
> 
> Why do we need a unicode string here?

The reason for this is that 2to3 changed the import of StringIO, since
cStringIO is not available in python3:

http://stackoverflow.com/questions/11914472/stringio-in-python3

Unfortunately, io.StringIO only accepts unicode arguments, not plain str.
Note that in python3, there is no such thing as the unicode type; str is
now a Unicode string, which is why it's different between the two.

> 
> I also had to use this patch or the file generation would first error
> out, and then would contain some *ptr += 1.0; rather than *ptr += 1;
> With these changes, the files are the same when generated with python2
> or python3 on my system (python3-3.4.2-4.fc22.x86_64)

Ah, yes.  That's one of the other big changes in python3: integer division.
The proper python3 way to do it is the // operator, which has apparently been
available in python2 since 2.2:

https://docs.python.org/release/2.2.3/whatsnew/node7.html


More information about the Spice-devel mailing list