Skip to content

Commit 5694201

Browse files
committed
extmod/vfs_fat_file: Make file.close() a no-op if file already closed.
As per CPython semantics. In particular, file.__del__() should not raise an exception if the file is already closed.
1 parent 06e7032 commit 5694201

3 files changed

Lines changed: 7 additions & 9 deletions

File tree

extmod/vfs_fat_file.c

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(file_obj_flush_obj, file_obj_flush);
120120

121121
STATIC mp_obj_t file_obj_close(mp_obj_t self_in) {
122122
pyb_file_obj_t *self = MP_OBJ_TO_PTR(self_in);
123-
FRESULT res = f_close(&self->fp);
124-
if (res != FR_OK) {
125-
mp_raise_OSError(fresult_to_errno_table[res]);
123+
// if fs==NULL then the file is closed and in that case this method is a no-op
124+
if (self->fp.fs != NULL) {
125+
FRESULT res = f_close(&self->fp);
126+
if (res != FR_OK) {
127+
mp_raise_OSError(fresult_to_errno_table[res]);
128+
}
126129
}
127130
return mp_const_none;
128131
}

tests/extmod/vfs_fat_fileio.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ def ioctl(self, op, arg):
4848
f.write("hello!")
4949
f.flush()
5050
f.close()
51+
f.close() # allowed
5152
try:
5253
f.write("world!")
5354
except OSError as e:
@@ -63,11 +64,6 @@ def ioctl(self, op, arg):
6364
except OSError as e:
6465
print(e.args[0] == uerrno.EINVAL)
6566

66-
try:
67-
f.close()
68-
except OSError as e:
69-
print(e.args[0] == uerrno.EINVAL)
70-
7167
try:
7268
vfs.open("foo_file.txt", "x")
7369
except OSError as e:

tests/extmod/vfs_fat_fileio.py.exp

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ True
33
True
44
True
55
True
6-
True
76
hello!world!
87
12
98
h

0 commit comments

Comments
 (0)