[openstack-dev] [nova] Port Nova to Python 3

Victor Stinner vstinner at redhat.com
Mon May 11 12:06:46 UTC 2015


Hi,

> Oh, this makes me think: how would one fix something like this?

The wiki page already contains some answer:
https://wiki.openstack.org/wiki/Python3#Common_patterns

Don't hesitate to complete the page if needed.

See also my personal list of documents:
https://haypo-notes.readthedocs.org/python.html#port-python-2-code-to-python-3


>      def unicode_convert(self, item):
>          try:
>  >           return unicode(item, "utf-8")
> E           NameError: name 'unicode' is not defined

Use six.text_type.


>      def make(self, idp, sp, args):
>          md5 = hashlib.md5()
>          for arg in args:
>              md5.update(arg.encode("utf-8"))
>  >       md5.update(sp)
> E       TypeError: Unicode-objects must be encoded before hashing

It depends on the code. Sometimes, you should encode sp in the caller, sometimes you should encode just before calling make(). If you don't know, use:

if isinstance(sp, six.text_type):
    sp = sp.encode("utf-8")
md5.update(sp)


> and one last one:
> 
>      def harvest_element_tree(self, tree):
>          # Fill in the instance members from the contents of the
>          # XML tree.
>          for child in tree:
>              self._convert_element_tree_to_member(child)
>  >       for attribute, value in tree.attrib.iteritems():
>              self._convert_element_attribute_to_member(attribute, value)
> E           AttributeError: 'dict' object has no attribute 'iteritems'

Use six.iteritems().


> BTW, I did this:
> -from Cookie import SimpleCookie
> +try:
> +    from Cookie import SimpleCookie
> +except:
> +    from http.cookies import SimpleCookie
> 
> Is there anything smarter to do with six? What's the rule with
> six.moves? Should I always just use the new location?

I did the same. If it's a very common pattern in your code, you can register you own "move" in six.moves:
https://pythonhosted.org/six/#advanced-customizing-renames

We used that fox mox/mox3 in tests of Oslo projects.


> Also, is this a correct fix for the basestring issue in Py3?
> 
> +try:
> +    basestring
> +except NameError:
> +    basestring = (str,bytes)

I prefer six.string_types.

Victor



More information about the OpenStack-dev mailing list