Skip to content

Commit 447838f

Browse files
committed
BUG: doing a class method lookup in __dealloc__ is dangerous
1 parent 776857a commit 447838f

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

pandas/_libs/parsers.pyx

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,21 @@ cdef extern from "parser/io.h":
294294
size_t *bytes_read, int *status, const char *encoding_errors)
295295

296296

297+
# Factor out code common to TextReader.__dealloc__ and TextReader.close
298+
# It cannot be a class method, since calling self.close() in __dealloc__
299+
# which causes a class attribute lookup and violates best parctices
300+
# https://cython.readthedocs.io/en/latest/src/userguide/special_methods.html#finalization-method-dealloc
301+
def _close(reader):
302+
# also preemptively free all allocated memory
303+
parser_free(reader.parser)
304+
if reader.true_set:
305+
kh_destroy_str_starts(reader.true_set)
306+
reader.true_set = NULL
307+
if reader.false_set:
308+
kh_destroy_str_starts(reader.false_set)
309+
reader.false_set = NULL
310+
311+
297312
cdef class TextReader:
298313
"""
299314
@@ -558,18 +573,11 @@ cdef class TextReader:
558573
pass
559574

560575
def __dealloc__(self):
561-
self.close()
576+
_close()
562577
parser_del(self.parser)
563578

564-
def close(self) -> None:
565-
# also preemptively free all allocated memory
566-
parser_free(self.parser)
567-
if self.true_set:
568-
kh_destroy_str_starts(self.true_set)
569-
self.true_set = NULL
570-
if self.false_set:
571-
kh_destroy_str_starts(self.false_set)
572-
self.false_set = NULL
579+
def close(self):
580+
_close(self)
573581

574582
def _set_quoting(self, quote_char: str | bytes | None, quoting: int):
575583
if not isinstance(quoting, int):

0 commit comments

Comments
 (0)