'Mocking python's native `open` function in imported modules [duplicate]

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?



Solution 1:[1]

I just found it thanks to this question. Need to import builtins:

import pathlib
import mock
import builtins

if __name__=="__main__":
  file_path = pathlib.Path('test.txt')  
  builtins.open = mock.open
  import main
  file_path.unlink()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user32882