Joel B
Joel B

Reputation: 13110

Undo Overwrite of Python Built-In

In Python there are several built-in functions. Take open for example open. I can fire up a Python console and get some info about open by doing the following:

>> open    
>>(built-in function open)

But if I were to do something like this:

>> # I know it's bad practice to import all items from the namespace    
>> from gzip import *    
>> open    
>>(function open at 0x26E88F0)

It appears that, for the rest of my console session, all calls to the open function will not use the built-in function but the one in the gzip module. Is there any way to redefine a built-in function in Python back to the original? It's easy if I have a reference to the desired function, like below:

def MyOpen(path):
  print('Trivial example')

open = MyOpen

How do you obtain a reference for built-in functions once those references have been overwritten?

Upvotes: 7

Views: 3015

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122172

You can simply delete the global:

del open

or you can import the __builtin__ module (Python 2) or builtins module (Python 3) to get to the original:

import __builtin__

__builtin__.open

Name lookups go first to your global namespace, then to the built-ins namespace; if you delete the global name open it'll no longer be in the way and the name lookup progresses to the built-ins namespace, or you can access that namespace directly via the imported module.

Upvotes: 21

Related Questions