1

I was asked to add some feature to the code originally written by other guys. There is a python code defines a function which overwrites the build in open function

def open(xxx):
   ...

I would like to access original open function in the same python file.

The best way is to change the name of self defined open. But I prefer not to change it since it is a hug system which may have many other files access to this method.

So, is there a way to access the build in open even if it has been overwritten?

user1817188
  • 487
  • 1
  • 7
  • 14

3 Answers3

4

Python 2:

>>> import __builtin__
>>> __builtin__.open
<built-in function open>

Python 3:

>>> import builtins
>>> builtins.open
<built-in function open>

Don't use __builtins__ :

From the docs:

CPython implementation detail: Users should not touch __builtins__; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should import the __builtin__ (no ā€˜s’) module and modify its attributes appropriately.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4
>>> __builtins__.open
<built-in function open>

Works the same in Python2 and Python3

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

A more general way to access an overwritten version of a function is this:

oldVersionOfOpen = open
def open(...):
    oldVersionOfOpen(...)

In fact, functions are only variables with a value (which is a callable), so you also can assign them to other variables to store them.

You could even do it like this:

def newOpen(...):
    pass  # do whatever you'd like to, even using originalOpen()

originalOpen, open = open, newOpen  # switch
Alfe
  • 56,346
  • 20
  • 107
  • 159