Tomáš Zato
Tomáš Zato

Reputation: 53161

How to get the original version of overriden builtin method on builtins module?

At some arbitrary place in code, this exists:

builtins.open = my_open

I cannot change that code, but it's broken. I need to make sure any open calls, including those from other builtin libraries use the original open. What I need is something like:

orig_open = get_original_method("open")
builtins.open = orig_open

In Javascript, I typically solved that issue by creating new window frame and getting the methods from there. How to do it in python?

Upvotes: 1

Views: 113

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160447

If the issue here is simply the open function, you can always grab io.open which is an alias for it:

import io
builtins.open = io.open

I am not aware of any generic solutions to this even though I would not be surprised if one existed.

Upvotes: 2

Chris
Chris

Reputation: 22953

I'm not exactly sure what you want, but you can use the __builtins__ magic variable to grab the "original" open function:

>>> builtins.open = __builtins__.open

The "magic variable" is simply an alias for the builtins module:

>>> __builtins__
<module 'builtins' (built-in)>
>>> 

You should note however that this is an implementation detail, and other versions of the Python interpreter might not support it. From the Python 3 documentation on the builtins module.

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. [...] Since this is an implementation detail, it may not be used by alternate implementations of Python.

Upvotes: 0

Related Questions