Skip to content

Commit c61ce96

Browse files
committed
unix file: Implement context manager protocol (for "with" statement).
1 parent 98a627d commit c61ce96

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

tests/io/file-with.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
f = open("io/data/file1")
2+
3+
with f as f2:
4+
print(f2.read())
5+
6+
# File should be closed
7+
try:
8+
f.read()
9+
except:
10+
# Note: CPython and us throw different exception trying to read from
11+
# close file.
12+
print("can't read file after with")

unix/file.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ static mp_obj_t fdfile_close(mp_obj_t self_in) {
4949
}
5050
static MP_DEFINE_CONST_FUN_OBJ_1(fdfile_close_obj, fdfile_close);
5151

52+
mp_obj_t fdfile___exit__(uint n_args, const mp_obj_t *args) {
53+
return fdfile_close(args[0]);
54+
}
55+
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fdfile___exit___obj, 4, 4, fdfile___exit__);
56+
5257
static mp_obj_t fdfile_fileno(mp_obj_t self_in) {
5358
mp_obj_fdfile_t *self = self_in;
5459
return MP_OBJ_NEW_SMALL_INT((machine_int_t)self->fd);
@@ -112,6 +117,8 @@ STATIC const mp_map_elem_t rawfile_locals_dict_table[] = {
112117
{ MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj},
113118
{ MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj },
114119
{ MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&fdfile_close_obj },
120+
{ MP_OBJ_NEW_QSTR(MP_QSTR___enter__), (mp_obj_t)&mp_identity_obj },
121+
{ MP_OBJ_NEW_QSTR(MP_QSTR___exit__), (mp_obj_t)&fdfile___exit___obj },
115122
};
116123

117124
STATIC MP_DEFINE_CONST_DICT(rawfile_locals_dict, rawfile_locals_dict_table);

0 commit comments

Comments
 (0)