Navigation

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 can be downloaded on PyPi. Its bug tracker and code hosting is on BitBucket.

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.

Indices and tables¶

  • Index
  • Search Page

Package contents¶

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 and new-style classes. In Python 3, this is just new-styles.

six.integer_types

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

six.string_types

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

six.text_type

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

six.binary_type

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

six.MAXSIZE

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

Here’s example usage of the module:

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 intepreter data structures. The following accessors are available. Note that the recommended way to inspect functions and methods is the stdlib inspect module.

six.get_unbound_function(meth)

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:

from six import get_unbound_function

class X(object):
    def method(self):
        pass
method_function = get_unbound_function(X.method)
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_code(func)

Get the code object associated with func.

six.get_function_defaults(func)

Get the defaults tuple associated with func.

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

Get the next item of iterator it. 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.

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)

Returns an iterator over dictionary‘s keys. This replaces dictionary.iterkeys() on Python 2 and dictionary.keys() on Python 3.

six.itervalues(dictionary)

Returns an iterator over dictionary‘s values. This replaces dictionary.itervalues() on Python 2 and dictionary.values() on Python 3.

six.iteritems(dictionary)

Returns an iterator over dictionary‘s items. This replaces dictionary.iteritems() on Python 2 and dictionary.items() on Python 3.

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 object.)

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=" ")

Print args into file. Each argument will be separated with sep and end will be written to the file at the last.

Note

In Python 2, this function imitates Python 3’s print() by not having softspace support. If you don’t know what that is, you’re probably ok. :)

six.reraise(exc_type, exc_value, exc_traceback=None)

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.

six.with_metaclass(metaclass, base=object)

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

from six import with_metaclass

class Meta(type):
    pass

class Base(object):
    pass

class MyClass(with_metaclass(Meta, Base)):
    pass

Binary and text data¶

Python 3 enforces the distinction between byte strings and text strings far more rigoriously 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)

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

six.u(text)

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.

Note

In Python 3.3, the u prefix has been reintroduced. Code that only supports Python 3 versions greater than 3.3 thus does not need u(). Additionally, since all Python versions 2.6 and after support the b prefix, b(), code without 2.5 support doesn’t need b().

six.int2byte(i)

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

six.StringIO

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

six.BytesIO

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

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:

from six.moves import html_parser

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

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 appropiate 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.

Note

The urllib, urllib2, and urlparse modules have been combined in the urllib package in Python 3. six.moves doesn’t not support their renaming because their members have been mixed across several modules in that package.

Supported renames:

Name Python 2 name Python 3 name
builtins __builtin__ builtins
configparser ConfigParser configparser
copyreg copy_reg copyreg
cPickle cPickle pickle
cStringIO cStringIO.StringIO() io.StringIO
filter itertools.ifilter() filter()
http_cookiejar cookielib http.cookiejar
http_cookies Cookie http.cookies
html_entities htmlentitydefs html.entities
html_parser HTMLParser html.parser
http_client httplib http.client
BaseHTTPServer BaseHTTPServer http.server
CGIHTTPServer CGIHTTPServer http.server
SimpleHTTPServer SimpleHTTPServer http.server
input raw_input() input()
map itertools.imap() map()
queue Queue queue
reduce reduce() functools.reduce()
reload_module reload() imp.reload()
reprlib repr reprlib
socketserver SocketServer socketserver
tkinter Tkinter tkinter
tkinter_dialog Dialog tkinter.dialog
tkinter_filedialog FileDialog tkinter.FileDialog
tkinter_scrolledtext ScrolledText tkinter.scolledtext
tkinter_simpledialog SimpleDialog tkinter.simpledialog
tkinter_tix Tix tkinter.tix
tkinter_constants Tkconstants tkinter.constants
tkinter_dnd Tkdnd tkinter.dnd
tkinter_colorchooser tkColorChooser tkinter.colorchooser
tkinter_commondialog tkCommonDialog tkinter.commondialog
tkinter_tkfiledialog tkFileDialog tkinter.filedialog
tkinter_font tkFont tkinter.font
tkinter_messagebox tkMessageBox tkinter.messagebox
tkinter_tksimpledialog tkSimpleDialog tkinter.simpledialog
urllib_robotparser robotparser urllib.robotparser
winreg _winreg winreg
xrange xrange() range()
zip itertools.izip() zip()

Advanced - Customizing renames¶

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

six.add_move(item)

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

six.remove_move(name)

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
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.