Six: Python 2 and 3 Compatibility Library

Six provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification. six consists of only one Python file, so it is painless to copy into a project.

Six can be downloaded on PyPI. Its bug tracker and code hosting is on GitHub.

The name, “six”, comes from the fact that 2*3 equals 6. Why not addition? Multiplication is more powerful, and, anyway, “five” has already been snatched away by the (admittedly now moribund) Zope Five project.

six.PY2

A boolean indicating if the code is running on Python 2.

six.PY3

A boolean indicating if the code is running on Python 3.

Constants

Six provides constants that may differ between Python versions. Ones ending _types are mostly useful as the second argument to isinstance or issubclass.

six.class_types

Possible class types. In Python 2, this encompasses old-style py2:types.ClassType and new-style type classes. In Python 3, this is just type.

six.integer_types

Possible integer types. In Python 2, this is py2:long() and py2:int(), and in Python 3, just py3:int().

six.string_types

Possible types for text data. This is py2:basestring() in Python 2 and py3:str() in Python 3.

six.text_type

Type for representing (Unicode) textual data. This is py2:unicode() in Python 2 and py3:str() in Python 3.

six.binary_type

Type for representing binary data. This is py2:str() in Python 2 and py3:bytes() in Python 3.

six.MAXSIZE

The maximum size of a container like py3:list() or py3:dict(). This is equivalent to py3:sys.maxsize in Python 2.6 and later (including 3.x). Note, this is temptingly similar to, but not the same as py2:sys.maxint in Python 2. There is no direct equivalent to py2:sys.maxint in Python 3 because its integer type has no limits aside from memory.

Here’s example usage of the module:

Copy
Copied!
            

import six def dispatch_types(value): if isinstance(value, six.integer_types): handle_integer(value) elif isinstance(value, six.class_types): handle_class(value) elif isinstance(value, six.string_types): handle_string(value)


Object model compatibility

Python 3 renamed the attributes of several interpreter data structures. The following accessors are available. Note that the recommended way to inspect functions and methods is the stdlib py3:inspect module.

six.get_unbound_function(meth)[source]

Get the function out of unbound method meth. In Python 3, unbound methods don’t exist, so this function just returns meth unchanged. Example usage:

six.get_method_function(meth)

Get the function out of method object meth.

six.get_method_self(meth)

Get the self of bound method meth.

six.get_function_closure(func)

Get the closure (list of cells) associated with func. This is equivalent to func.__closure__ on Python 2.6+ and func.func_closure on Python 2.5.

six.get_function_code(func)

Get the code object associated with func. This is equivalent to func.__code__ on Python 2.6+ and func.func_code on Python 2.5.

six.get_function_defaults(func)

Get the defaults tuple associated with func. This is equivalent to func.__defaults__ on Python 2.6+ and func.func_defaults on Python 2.5.

six.get_function_globals(func)

Get the globals of func. This is equivalent to func.__globals__ on Python 2.6+ and func.func_globals on Python 2.5.

six.next(it)
six.advance_iterator(it)

Get the next item of iterator it. py3:StopIteration is raised if the iterator is exhausted. This is a replacement for calling it.next() in Python 2 and next(it) in Python 3. Python 2.6 and above have a builtin next function, so six’s version is only necessary for Python 2.5 compatibility.

six.callable(obj)

Check if obj can be called. Note callable has returned in Python 3.2, so using six’s version is only necessary when supporting Python 3.0 or 3.1.

six.iterkeys(dictionary, **kwargs)[source]

Returns an iterator over dictionary’s keys. This replaces dictionary.iterkeys() on Python 2 and dictionary.keys() on Python 3. kwargs are passed through to the underlying method.

six.itervalues(dictionary, **kwargs)[source]

Returns an iterator over dictionary’s values. This replaces dictionary.itervalues() on Python 2 and dictionary.values() on Python 3. kwargs are passed through to the underlying method.

six.iteritems(dictionary, **kwargs)[source]

Returns an iterator over dictionary’s items. This replaces dictionary.iteritems() on Python 2 and dictionary.items() on Python 3. kwargs are passed through to the underlying method.

six.iterlists(dictionary, **kwargs)[source]

Calls dictionary.iterlists() on Python 2 and dictionary.lists() on Python 3. No builtin Python mapping type has such a method; this method is intended for use with multi-valued dictionaries like Werkzeug’s. kwargs are passed through to the underlying method.

six.viewkeys(dictionary)

Return a view over dictionary’s keys. This replaces py2:dict.viewkeys() on Python 2.7 and py3:dict.keys() on Python 3.

six.viewvalues(dictionary)

Return a view over dictionary’s values. This replaces py2:dict.viewvalues() on Python 2.7 and py3:dict.values() on Python 3.

six.viewitems(dictionary)

Return a view over dictionary’s items. This replaces py2:dict.viewitems() on Python 2.7 and py3:dict.items() on Python 3.

six.create_bound_method(func, obj)

Return a method object wrapping func and bound to obj. On both Python 2 and 3, this will return a py3:types.MethodType() object. The reason this wrapper exists is that on Python 2, the MethodType constructor requires the obj’s class to be passed.

six.create_unbound_method(func, cls)[source]

Return an unbound method object wrapping func. In Python 2, this will return a py2:types.MethodType() object. In Python 3, unbound methods do not exist and this wrapper will simply return func.

class six.Iterator

A class for making portable iterators. The intention is that it be subclassed and subclasses provide a __next__ method. In Python 2, Iterator has one method: next. It simply delegates to __next__. An alternate way to do this would be to simply alias next to __next__. However, this interacts badly with subclasses that override __next__. Iterator is empty on Python 3. (In fact, it is just aliased to py3:object.)

@six.wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES)[source]

This is exactly the py3:functools.wraps() decorator, but it sets the __wrapped__ attribute on what it decorates as py3:functools.wraps() does on Python versions after 3.2.

Syntax compatibility

These functions smooth over operations which have different syntaxes between Python 2 and 3.

six.exec_(code, globals=None, locals=None)

Execute code in the scope of globals and locals. code can be a string or a code object. If globals or locals are not given, they will default to the scope of the caller. If just globals is given, it will also be used as locals.

six.print_(*args, *, file=sys.stdout, end="\n", sep=" ", flush=False)

Print args into file. Each argument will be separated with sep and end will be written to the file after the last argument is printed. If flush is true, file.flush() will be called after all data is written.

six.raise_from(exc_value, exc_value_from)[source]

Raise an exception from a context. On Python 3, this is equivalent to raise exc_value from exc_value_from. On Python 2, which does not support exception chaining, it is equivalent to raise exc_value.

six.reraise(exc_type, exc_value, exc_traceback=None)[source]

Reraise an exception, possibly with a different traceback. In the simple case, reraise(*sys.exc_info()) with an active exception (in an except block) reraises the current exception with the last traceback. A different traceback can be specified with the exc_traceback parameter. Note that since the exception reraising is done within the reraise() function, Python will attach the call frame of reraise() to whatever traceback is raised.

six.with_metaclass(metaclass, *bases)[source]

Create a new class with base classes bases and metaclass metaclass. This is designed to be used in class declarations like this:

Another way to set a metaclass on a class is with the add_metaclass() decorator.

@six.add_metaclass(metaclass)[source]

Class decorator that replaces a normally-constructed class with a metaclass-constructed one. Example usage:

That code produces a class equivalent to

on Python 3 or

on Python 2.

Note that class decorators require Python 2.6. However, the effect of the decorator can be emulated on Python 2.5 like so:

Binary and text data

Python 3 enforces the distinction between byte strings and text strings far more rigorously than Python 2 does; binary data cannot be automatically coerced to or from text data. six provides several functions to assist in classifying string data in all Python versions.

six.b(data)[source]

A “fake” bytes literal. data should always be a normal string literal. In Python 2, b() returns an 8-bit string. In Python 3, data is encoded with the latin-1 encoding to bytes.

six.u(text)[source]

A “fake” unicode literal. text should always be a normal string literal. In Python 2, u() returns unicode, and in Python 3, a string. Also, in Python 2, the string is decoded with the unicode-escape codec, which allows unicode escapes to be used in it.

six.unichr(c)

Return the (Unicode) string representing the codepoint c. This is equivalent to py2:unichr() on Python 2 and py3:chr() on Python 3.

six.int2byte(i)

Converts i to a byte. i must be in range(0, 256). This is equivalent to py2:chr() in Python 2 and bytes((i,)) in Python 3.

six.byte2int(bs)

Converts the first byte of bs to an integer. This is equivalent to ord(bs[0]) on Python 2 and bs[0] on Python 3.

six.indexbytes(buf, i)

Return the byte at index i of buf as an integer. This is equivalent to indexing a bytes object in Python 3.

six.iterbytes(buf)

Return an iterator over bytes in buf as integers. This is equivalent to a bytes object iterator in Python 3.

six.ensure_binary(s, encoding='utf-8', errors='strict')

Coerce s to binary_type. encoding, errors are the same as py3:str.encode()

six.ensure_str(s, encoding='utf-8', errors='strict')

Coerce s to str. encoding, errors are the same py3:str.encode()

six.ensure_text(s, encoding='utf-8', errors='strict')

Coerce s to text_type. encoding, errors are the same as py3:str.encode()

six.StringIO

This is a fake file object for textual data. It’s an alias for py2:StringIO.StringIO in Python 2 and py3:io.StringIO in Python 3.

six.BytesIO

This is a fake file object for binary data. In Python 2, it’s an alias for py2:StringIO.StringIO, but in Python 3, it’s an alias for py3:io.BytesIO.

@six.python_2_unicode_compatible[source]

A class decorator that takes a class defining a __str__ method. On Python 3, the decorator does nothing. On Python 2, it aliases the __str__ method to __unicode__ and creates a new __str__ method that returns the result of __unicode__() encoded with UTF-8.

unittest assertions

Six contains compatibility shims for unittest assertions that have been renamed. The parameters are the same as their aliases, but you must pass the test method as the first argument. For example:

Copy
Copied!
            

import six import unittest class TestAssertCountEqual(unittest.TestCase): def test(self): six.assertCountEqual(self, (1, 2), [2, 1])

Note these functions are only available on Python 2.7 or later.

six.assertCountEqual()[source]

Alias for assertCountEqual() on Python 3 and assertItemsEqual() on Python 2.

six.assertRaisesRegex()[source]

Alias for assertRaisesRegex() on Python 3 and assertRaisesRegexp() on Python 2.

six.assertRegex()[source]

Alias for assertRegex() on Python 3 and assertRegexpMatches() on Python 2.

Renamed modules and attributes compatibility

Python 3 reorganized the standard library and moved several functions to different modules. Six provides a consistent interface to them through the fake six.moves module. For example, to load the module for parsing HTML on Python 2 or 3, write:

Copy
Copied!
            

from six.moves import html_parser

Similarly, to get the function to reload modules, which was moved from the builtin module to the importlib module, use:

Copy
Copied!
            

from six.moves import reload_module

For the most part, six.moves aliases are the names of the modules in Python 3. When the new Python 3 name is a package, the components of the name are separated by underscores. For example, html.parser becomes html_parser. In some cases where several modules have been combined, the Python 2 name is retained. This is so the appropriate modules can be found when running on Python 2. For example, BaseHTTPServer which is in http.server in Python 3 is aliased as BaseHTTPServer.

Some modules which had two implementations have been merged in Python 3. For example, cPickle no longer exists in Python 3; it was merged with pickle. In these cases, fetching the fast version will load the fast one on Python 2 and the merged module in Python 3.

The py2:urllib, py2:urllib2, and py2:urlparse modules have been combined in the py3:urllib package in Python 3. The six.moves.urllib package is a version-independent location for this functionality; its structure mimics the structure of the Python 3 py3:urllib package.

Note

In order to make imports of the form:

Copy
Copied!
            

from six.moves.cPickle import loads

work, six places special proxy objects in py3:sys.modules. These proxies lazily load the underlying module when an attribute is fetched. This will fail if the underlying module is not available in the Python interpreter. For example, sys.modules["six.moves.winreg"].LoadKey would fail on any non-Windows platform. Unfortunately, some applications try to load attributes on every module in py3:sys.modules. six mitigates this problem for some applications by pretending attributes on unimportable modules do not exist. This hack does not work in every case, though. If you are encountering problems with the lazy modules and don’t use any from imports directly from six.moves modules, you can workaround the issue by removing the six proxy modules:

Copy
Copied!
            

d = [name for name in sys.modules if name.startswith("six.moves.")] for name in d: del sys.modules[name]

Supported renames:

Name Python 2 name Python 3 name
builtins py2:__builtin__ py3:builtins
configparser py2:ConfigParser py3:configparser
copyreg py2:copy_reg py3:copyreg
cPickle py2:cPickle py3:pickle
cStringIO py2:cStringIO.StringIO() py3:io.StringIO
dbm_gnu py2:gdbm() py3:dbm.gnu
_dummy_thread py2:dummy_thread py3:_dummy_thread
email_mime_base py2:email.MIMEBase py3:email.mime.base
email_mime_image py2:email.MIMEImage py3:email.mime.image
email_mime_multipart py2:email.MIMEMultipart py3:email.mime.multipart
email_mime_nonmultipart py2:email.MIMENonMultipart py3:email.mime.nonmultipart
email_mime_text py2:email.MIMEText py3:email.mime.text
filter py2:itertools.ifilter() py3:filter()
filterfalse py2:itertools.ifilterfalse() py3:itertools.filterfalse()
getcwd py2:os.getcwdu() py3:os.getcwd()
getcwdb py2:os.getcwd() py3:os.getcwdb()
getoutput py2:commands.getoutput() py3:subprocess.getoutput()
http_cookiejar py2:cookielib py3:http.cookiejar
http_cookies py2:Cookie py3:http.cookies
html_entities py2:htmlentitydefs py3:html.entities
html_parser py2:HTMLParser py3:html.parser
http_client py2:httplib py3:http.client
BaseHTTPServer py2:BaseHTTPServer py3:http.server
CGIHTTPServer py2:CGIHTTPServer py3:http.server
SimpleHTTPServer py2:SimpleHTTPServer py3:http.server
input py2:raw_input() py3:input()
intern py2:intern() py3:sys.intern()
map py2:itertools.imap() py3:map()
queue py2:Queue py3:queue
range py2:xrange() py3:range()
reduce py2:reduce() py3:functools.reduce()
reload_module py2:reload() py3:imp.reload(), py3:importlib.reload() on Python 3.4+
reprlib py2:repr py3:reprlib
shlex_quote py2:pipes.quote py3:shlex.quote
socketserver py2:SocketServer py3:socketserver
_thread py2:thread py3:_thread
tkinter py2:Tkinter py3:tkinter
tkinter_dialog py2:Dialog py3:tkinter.dialog
tkinter_filedialog py2:FileDialog py3:tkinter.FileDialog
tkinter_scrolledtext py2:ScrolledText py3:tkinter.scrolledtext
tkinter_simpledialog py2:SimpleDialog py3:tkinter.simpledialog
tkinter_ttk py2:ttk py3:tkinter.ttk
tkinter_tix py2:Tix py3:tkinter.tix
tkinter_constants py2:Tkconstants py3:tkinter.constants
tkinter_dnd py2:Tkdnd py3:tkinter.dnd
tkinter_colorchooser py2:tkColorChooser py3:tkinter.colorchooser
tkinter_commondialog py2:tkCommonDialog py3:tkinter.commondialog
tkinter_tkfiledialog py2:tkFileDialog py3:tkinter.filedialog
tkinter_font py2:tkFont py3:tkinter.font
tkinter_messagebox py2:tkMessageBox py3:tkinter.messagebox
tkinter_tksimpledialog py2:tkSimpleDialog py3:tkinter.simpledialog
urllib.parse See six.moves.urllib.parse py3:urllib.parse
urllib.error See six.moves.urllib.error py3:urllib.error
urllib.request See six.moves.urllib.request py3:urllib.request
urllib.response See six.moves.urllib.response py3:urllib.response
urllib.robotparser py2:robotparser py3:urllib.robotparser
urllib_robotparser py2:robotparser py3:urllib.robotparser
UserDict py2:UserDict.UserDict py3:collections.UserDict
UserList py2:UserList.UserList py3:collections.UserList
UserString py2:UserString.UserString py3:collections.UserString
winreg py2:_winreg py3:winreg
xmlrpc_client py2:xmlrpclib py3:xmlrpc.client
xmlrpc_server py2:SimpleXMLRPCServer py3:xmlrpc.server
xrange py2:xrange() py3:range()
zip py2:itertools.izip() py3:zip()
zip_longest py2:itertools.izip_longest() py3:itertools.zip_longest()

urllib parse

Contains functions from Python 3’s py3:urllib.parse and Python 2’s:

py2:urlparse:

  • py2:urlparse.ParseResult()
  • py2:urlparse.SplitResult()
  • py2:urlparse.urlparse()
  • py2:urlparse.urlunparse()
  • py2:urlparse.parse_qs()
  • py2:urlparse.parse_qsl()
  • py2:urlparse.urljoin()
  • py2:urlparse.urldefrag()
  • py2:urlparse.urlsplit()
  • py2:urlparse.urlunsplit()
  • py2:urlparse.splitquery()
  • py2:urlparse.uses_fragment()
  • py2:urlparse.uses_netloc()
  • py2:urlparse.uses_params()
  • py2:urlparse.uses_query()
  • py2:urlparse.uses_relative()

and py2:urllib:

  • py2:urllib.quote()
  • py2:urllib.quote_plus()
  • py2:urllib.splittag()
  • py2:urllib.splituser()
  • py2:urllib.splitvalue()
  • py2:urllib.unquote() (also exposed as py3:urllib.parse.unquote_to_bytes())
  • py2:urllib.unquote_plus()
  • py2:urllib.urlencode()

urllib error

Contains exceptions from Python 3’s py3:urllib.error and Python 2’s:

py2:urllib:

  • py2:urllib.ContentTooShortError

and py2:urllib2:

  • py2:urllib2.URLError
  • py2:urllib2.HTTPError

urllib request

Contains items from Python 3’s py3:urllib.request and Python 2’s:

py2:urllib:

  • py2:urllib.pathname2url()
  • py2:urllib.url2pathname()
  • py2:urllib.getproxies()
  • py2:urllib.urlretrieve()
  • py2:urllib.urlcleanup()
  • py2:urllib.URLopener
  • py2:urllib.FancyURLopener
  • py2:urllib.proxy_bypass()

and py2:urllib2:

  • py2:urllib2.urlopen()
  • py2:urllib2.install_opener()
  • py2:urllib2.build_opener()
  • py2:urllib2.parse_http_list()
  • py2:urllib2.parse_keqv_list()
  • py2:urllib2.Request
  • py2:urllib2.OpenerDirector
  • py2:urllib2.HTTPDefaultErrorHandler
  • py2:urllib2.HTTPRedirectHandler
  • py2:urllib2.HTTPCookieProcessor
  • py2:urllib2.ProxyHandler
  • py2:urllib2.BaseHandler
  • py2:urllib2.HTTPPasswordMgr
  • py2:urllib2.HTTPPasswordMgrWithDefaultRealm
  • py2:urllib2.AbstractBasicAuthHandler
  • py2:urllib2.HTTPBasicAuthHandler
  • py2:urllib2.ProxyBasicAuthHandler
  • py2:urllib2.AbstractDigestAuthHandler
  • py2:urllib2.HTTPDigestAuthHandler
  • py2:urllib2.ProxyDigestAuthHandler
  • py2:urllib2.HTTPHandler
  • py2:urllib2.HTTPSHandler
  • py2:urllib2.FileHandler
  • py2:urllib2.FTPHandler
  • py2:urllib2.CacheFTPHandler
  • py2:urllib2.UnknownHandler
  • py2:urllib2.HTTPErrorProcessor

urllib response

Contains classes from Python 3’s py3:urllib.response and Python 2’s:

py2:urllib:

  • py2:urllib.addbase
  • py2:urllib.addclosehook
  • py2:urllib.addinfo
  • py2:urllib.addinfourl

Advanced - Customizing renames

It is possible to add additional names to the six.moves namespace.

six.add_move(item)[source]

Add item to the six.moves mapping. item should be a MovedAttribute or MovedModule instance.

six.remove_move(name)[source]

Remove the six.moves mapping called name. name should be a string.

Instances of the following classes can be passed to add_move(). Neither have any public members.

class six.MovedModule(name, old_mod, new_mod)[source]

Create a mapping for six.moves called name that references different modules in Python 2 and 3. old_mod is the name of the Python 2 module. new_mod is the name of the Python 3 module.

class six.MovedAttribute(name, old_mod, new_mod, old_attr=None, new_attr=None)[source]

Create a mapping for six.moves called name that references different attributes in Python 2 and 3. old_mod is the name of the Python 2 module. new_mod is the name of the Python 3 module. If new_attr is not given, it defaults to old_attr. If neither is given, they both default to name.

© Copyright 2018-2020, NVIDIA Corporation. Last updated on Oct 30, 2023.