I would like to overwrite python's native open function.
Here's what I have tried. I have the following files in a directory:
main.py
mock.py
test.txt
test_main.py
main.py contains the following:
fs = open('test.txt', 'r')
mock.py contains the following:
def open():
print("hello")
test.txt contains the following:
abc
test_main.py contains the following:
import pathlib
import mock
if __name__=="__main__":
file_path = pathlib.Path('test.txt')
open = mock.open
import main
file_path.unlink()
In line 6 of test_main.py I tried to overwrite by setting my own
function in mock.py to the keyword open. Within test_main.py
it looks like python will use my definition. However, within the
imported main.py it looks like python still resorts to the native definition, such that python test_main.py throws the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'test.txt'
How can I redefine open such that my definition applies to all
imported namespaces?