{"record":{"id":"9a07226e89563541","repo":"python/cpython","slug":"cannot-use-closefd-false-with-file-name","errorCode":null,"errorMessage":"Cannot use closefd=False with file name","messagePattern":"Cannot use closefd=False with file name","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Lib/_pyio.py","lineNumber":1604,"sourceCode":"\n        if self._readable and self._writable:\n            flags |= os.O_RDWR\n        elif self._readable:\n            flags |= os.O_RDONLY\n        else:\n            flags |= os.O_WRONLY\n\n        flags |= getattr(os, 'O_BINARY', 0)\n\n        noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or\n                          getattr(os, 'O_CLOEXEC', 0))\n        flags |= noinherit_flag\n\n        owned_fd = None\n        try:\n            if fd < 0:\n                if not closefd:\n                    raise ValueError('Cannot use closefd=False with file name')\n                if opener is None:\n                    fd = os.open(file, flags, 0o666)\n                else:\n                    fd = opener(file, flags)\n                    if not isinstance(fd, int):\n                        raise TypeError('expected integer from opener')\n                    if fd < 0:\n                        # bpo-27066: Raise a ValueError for bad value.\n                        raise ValueError(f'opener returned {fd}')\n                owned_fd = fd\n                if not noinherit_flag:\n                    os.set_inheritable(fd, False)\n\n            self._closefd = closefd\n            self._stat_atopen = os.fstat(fd)\n            try:\n                if stat.S_ISDIR(self._stat_atopen.st_mode):\n                    raise IsADirectoryError(errno.EISDIR,","sourceCodeStart":1586,"sourceCodeEnd":1622,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pyio.py#L1586-L1622","documentation":"Raised by FileIO.__init__ when a path (not an fd) is given together with closefd=False. closefd only has meaning for integer file descriptors — when FileIO opens the file itself from a name, it owns the resulting fd and must be able to close it; refusing closefd=False prevents a leaked fd that nothing else can manage.","triggerScenarios":"open(path, 'rb', closefd=False); io.FileIO('data.txt', 'r', closefd=False). Any call where file is a str/bytes/PathLike and closefd is falsy hits this branch because fd < 0 at that point.","commonSituations":"Copy-pasting closefd=False from code that wrapped an existing fd; wrapping a path-based helper that forwards **kwargs including closefd; library APIs that expose closefd for both fd and path inputs without branching.","solutions":["Drop closefd (or pass closefd=True) when opening by path — True is already the default","Only use closefd=False when passing an integer fd you want to keep open after the object is closed","In wrapper APIs, set closefd only for the fd branch: closefd=closefd if isinstance(file, int) else None"],"exampleFix":"# before\nf = open('data.bin', 'rb', closefd=False)  # ValueError\n\n# after\nf = open('data.bin', 'rb')                # closefd defaults to True for paths\n# closefd=False is only valid like this:\ng = open(fd, 'rb', closefd=False)","handlingStrategy":"validation","validationCode":"import os\nkwargs = {}\nif isinstance(file_arg, int) and not isinstance(file_arg, bool):\n    kwargs['closefd'] = closefd   # only meaningful for real fds\nf = open(file_arg, 'rb', **kwargs)","typeGuard":"def closefd_allowed(file):\n    return isinstance(file, int) and not isinstance(file, bool)","tryCatchPattern":"try:\n    f = open(path, 'rb', closefd=closefd)\nexcept ValueError as e:\n    if 'closefd' in str(e):\n        f = open(path, 'rb')  # retry with default closefd=True\n    else:\n        raise","preventionTips":["Only set closefd when the first argument is an integer fd","Default closefd=True is correct for path opens — omit the parameter","Audit helper functions that forward **kwargs into open()"],"tags":["python","io","file-io","closefd","valueerror"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}