sorin
sorin

Reputation: 170798

How to use python modules that were renamed 3 in a cross compatible way?

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)

Upvotes: 1

Views: 256

Answers (2)

Joschua
Joschua

Reputation: 6034

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!

Upvotes: 1

Ned Deily
Ned Deily

Reputation: 85105

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

Upvotes: 3

Related Questions