Working Around Shadowed Functions

Recently I ran into an issue where an application that calls Python would insert int into Python’s namespace, which overwrites Python’s built-in int function. Since I have to use the tool and I needed to use Python’s int function, I needed a way around this annoyance.

Fortunately, this is fairly easy to fix. All you need to do is import int from __builtin__ and rename it so you don’t overwrite the inserted version:

from __builtin__ import int as py_int

This gives you access to Python’s int function again, although it is now called py_int. You can name it whatever you like as long as you don’t name it int.

The most common circumstance where one shadows builtins or other variables is when the developer imports everything from a package or module:

from something import *

When you do an import like the one above, you don’t always know what all you have imported and you may end up writing your own variable or function that shadows one that you’ve imported. That is the main reason that importing everything from a package or module is so strongly discouraged.

Anyway, I hope you found this little tip helpful. In Python 3, the core developers added a builtins module basically for this very purpose.

4 thoughts on “Working Around Shadowed Functions”

  1. It should be

    from __builtin__ import int as py_int

    In Python 3 it’s

    from builtins import int as py_int

  2. So, who on earth thinks that they ought to be defining a different int() than the one that Guide has gifted to us? 🙂

  3. Brandon Rhodes

    So, who on earth thinks that they ought to be defining a different int() than the one that Guido has gifted to us? 🙂

  4. I am using a tool called Squish that is used for testing UI’s created in Qt. They insert ‘int” and “bool” (and maybe more) into the Python environment, so we have to work around that.

Comments are closed.