Python six.moves

The python six.moves command handles modules whose name changed in Python 3. It’s not that difficult to use. But in the version of PyCharm that I am using, the code is shown as an error. Since I do not use the command that often, I wrote these notes.

Expanding on the six docs example, the HTML parser:

  • It’s called HTMLParser in Python 2
  • Its’ called html.parser in Python 3

Your Python 2 code:

from six.moves import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Encountered a start tag:", tag

    def handle_endtag(self, tag):
        print "Encountered an end tag :", tag

    def handle_data(self, data):
        print "Encountered some data  :", data

becomes:

from six.moves import html_parser

class MyHTMLParser(html_parser):
    def handle_starttag(self, tag, attrs):
        print "Encountered a start tag:", tag

    def handle_endtag(self, tag):
        print "Encountered an end tag :", tag

    def handle_data(self, data):
        print "Encountered some data  :", data

Note this is a two step process:

  1. change the import statement
  2. scan your code for “HTMLParser” and replace it with “html_parser” (in the case of Python 2)

Things get a little more complicated where packages in Python 2 have been merged into one package in Python 3. For example,  the urllib, urllib2, and urlparse modules have been combined in the urllib package in Python 3. My original Python 2 code:

from urlparse import urlparse

query_string = urlparse(full_url).query

becomes

# To import just the urlparse module
from six.moves.urllib.parse import urlparse
query_string = urlparse(full_url).query

# Or to import the entire package.
import six.moves.urllib.parse as urlparse
query_string = urlparse.urlparse(full_url).query

Summary

To use six.moves, use the name in column 1 of the table in the docs for your imports. Then if your code is Python 2, do find on value in second column and replace it with column 1. If your code is Python 3, do find on value in third column and replace it with column 1.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s