Mon 16 Jun 2014
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 __builtins__ 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.