views:

49

answers:

2

There are several modules that were renamed in Python 3 and I'm looking for a solution that will make your code work in both python flavors.

In Python 3, __builtin__ was renamed to builtins. Example:

import __builtin__
#...
__builtin__.something # appearing multiple times ("something" may vary)
+1  A: 

You could solve the problem by using nested try .. except-blocks:

try:
    name = __builtins__.name
except NameError:
    try:
        name = builtins.name
    except NameError:
        name = __buildins__.name
        # if this will fail, the exception will be raised

This is no real code, just an example, but name will have the proper content, independent from your version. Inside of the blocks you could also import newname as oldname or copy the values from the new global builtins to the old __buildin__:

try:
    __builtins__ = builtins
except NameError:
    try:
        __builtins__ = buildins # just for example
    except NameError:
        __builtins__ = __buildins__
        # if this will fail, the exception will be raised

Now you can use __builtins__ just as in previous python-versions.

Hope it helps!

Joschua
Sorry, but "something" may vary. I modified the question to clarify this.
Sorin Sbarnea
+1  A: 

Benjamin Peterson's six may be what you are looking for. Six "provides simple utilities for wrapping over differences between Python 2 and Python 3". For example:

from six.moves import builtin  # works for both python 2 and 3
Ned Deily
Thanks, that solves even more py3 related problems. You could improve the answer a little bit including a small description of this module (just for other readers). Remark: six is very small and it is easy to include it in your package to minimize dependencies.
Sorin Sbarnea
Time machine strikes again: I just did.
Ned Deily