0

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?

user32882
  • 5,094
  • 5
  • 43
  • 82
  • If you want to shadow builtins across *all* modules, use the ``builtins`` module. ``open = mock.open`` just shadows the builtin in the current module. Still, it's probably a good idea to use an [actual mock library](https://docs.python.org/3/library/unittest.mock.html) instead. – MisterMiyagi Mar 12 '22 at 14:59

1 Answers1

0

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()
user32882
  • 5,094
  • 5
  • 43
  • 82