How can I override the built in open
function such that when I call it like so…
JavaScript
x
3
1
with open(file_path, "r") as f:
2
contents = f.read()
3
The contents
variable is any string I want?
EDIT: To clarify, I want to be able to just provide a string to the open function rather than a file path that will be read.
JavaScript
1
4
1
with open("foobar") as f:
2
contents = f.read()
3
print(contents)
4
The above should print foobar.
I am aware this is defeating the purpose of open etc but it is for testing purposes.
Advertisement
Answer
You can create your own file-like type and override the builtin open
with your own open
function.
JavaScript
1
30
30
1
import builtins
2
import contextlib
3
4
5
class File(object):
6
"""
7
A basic file-like object.
8
"""
9
10
def __init__(self, path, *args, **kwargs):
11
self._fobj = builtins.open(path, *args, **kwargs)
12
13
def read(self, n_bytes = -1):
14
data = self._fobj.read(n_bytes)
15
16
return data
17
18
def close(self):
19
self._fobj.close()
20
21
22
@contextlib.contextmanager
23
def open(path, *args, **kwargs):
24
fobj = File(path, *args, **kwargs)
25
try:
26
with contextlib.closing(fobj):
27
yield fobj
28
finally:
29
pass
30
You can add whatever behavior or additional logic needed to adjust the return value of read()
inside File.read
itself, or override the behavior entirely from a subclass of File
.
Simplified for the particular case in question:
JavaScript
1
16
16
1
class File(str):
2
def read(self):
3
return str(self)
4
5
6
@contextlib.contextmanager
7
def open(string):
8
try:
9
yield File(string)
10
finally:
11
pass
12
13
14
with open('foobar') as f:
15
print(f.read())
16