user1817188 user1817188 - 6 months ago 11
Python Question

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

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?

Answer

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.

Comments