From cfbdd6785c526e7787c955c13b6cad16484c62a0 Mon Sep 17 00:00:00 2001 From: Abolfazl Hosseini Date: Wed, 11 Mar 2026 12:56:40 +0330 Subject: [PATCH] Refactor PyFile_GetLine: reduce duplicated condition logic Consolidated repeated conditions `n < 0 && result != NULL` into a single check and handled the result type using PyBytes_Check and PyUnicode_Check inside the block. This reduces duplication and improves code readability while keeping the original behavior unchanged. --- Objects/fileobject.c | 47 +++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/Objects/fileobject.c b/Objects/fileobject.c index 05c3e75b4642ee..a6f46692ba29c6 100644 --- a/Objects/fileobject.c +++ b/Objects/fileobject.c @@ -73,31 +73,34 @@ PyFile_GetLine(PyObject *f, int n) Py_SETREF(result, NULL); } - if (n < 0 && result != NULL && PyBytes_Check(result)) { - const char *s = PyBytes_AS_STRING(result); - Py_ssize_t len = PyBytes_GET_SIZE(result); - if (len == 0) { - Py_SETREF(result, NULL); - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - (void) _PyBytes_Resize(&result, len-1); - } - } - if (n < 0 && result != NULL && PyUnicode_Check(result)) { - Py_ssize_t len = PyUnicode_GET_LENGTH(result); - if (len == 0) { - Py_SETREF(result, NULL); - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); + if(n < 0 && result != NULL) { + if (PyBytes_Check(result)) { + const char *s = PyBytes_AS_STRING(result); + Py_ssize_t len = PyBytes_GET_SIZE(result); + if (len == 0) { + Py_SETREF(result, NULL); + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + (void) _PyBytes_Resize(&result, len-1); + } } - else if (PyUnicode_READ_CHAR(result, len-1) == '\n') { - PyObject *v; - v = PyUnicode_Substring(result, 0, len-1); - Py_SETREF(result, v); + if (PyUnicode_Check(result)) { + Py_ssize_t len = PyUnicode_GET_LENGTH(result); + if (len == 0) { + Py_SETREF(result, NULL); + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (PyUnicode_READ_CHAR(result, len-1) == '\n') { + PyObject *v; + v = PyUnicode_Substring(result, 0, len-1); + Py_SETREF(result, v); + } } } + return result; }