Is it possible to access original function which has been overwritten in python

Question:

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?

Asked By: user1817188

||

Answers:

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.

Answered By: Ashwini Chaudhary
>>> __builtins__.open
<built-in function open>

Works the same in Python2 and Python3

Answered By: John La Rooy

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
Answered By: Alfe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.