{"record":{"id":"d43528eee9a89ad1","repo":"python/cpython","slug":"invalid-mode-s","errorCode":null,"errorMessage":"invalid mode: %s","messagePattern":"invalid mode: (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/_pyio.py","lineNumber":1560,"sourceCode":"            finally:\n                self._fd = -1\n\n        if isinstance(file, float):\n            raise TypeError('integer argument expected, got float')\n        if isinstance(file, int):\n            if isinstance(file, bool):\n                import warnings\n                warnings.warn(\"bool is used as a file descriptor\",\n                              RuntimeWarning, stacklevel=2)\n                file = int(file)\n            fd = file\n            if fd < 0:\n                raise ValueError('negative file descriptor')\n        else:\n            fd = -1\n\n        if not isinstance(mode, str):\n            raise TypeError('invalid mode: %s' % (mode,))\n        if not set(mode) <= set('xrwab+'):\n            raise ValueError('invalid mode: %s' % (mode,))\n        if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:\n            raise ValueError('Must have exactly one of create/read/write/append '\n                             'mode and at most one plus')\n\n        if 'x' in mode:\n            self._created = True\n            self._writable = True\n            flags = os.O_EXCL | os.O_CREAT\n        elif 'r' in mode:\n            self._readable = True\n            flags = 0\n        elif 'w' in mode:\n            self._writable = True\n            self._truncate = True\n            flags = os.O_CREAT | os.O_TRUNC\n        elif 'a' in mode:","sourceCodeStart":1542,"sourceCodeEnd":1578,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pyio.py#L1542-L1578","documentation":"Raised by FileIO.__init__ when the mode argument is not a str instance ('invalid mode: %s' % (mode,)). This is a TypeError raised before any mode-character validation, so even a plausible mode like b'rb' or a tuple fails here.","triggerScenarios":"open(path, b'rb', buffering=0) via io.FileIO; passing mode as None, an enum object, or bytes; a keyword mix-up where a non-string positional argument lands in the mode slot.","commonSituations":"Config-driven mode values loaded from JSON/YAML as non-strings; mixing bytes and str mode constants in code migrated from Python 2; passing an IntEnum or custom Mode class where a plain string is required.","solutions":["Pass mode as a plain str like 'rb', 'wb', 'r+b'","Normalize config values: mode = str(mode) if mode is not None else 'r'","Check for swapped positional arguments (file, mode) in the call"],"exampleFix":"# before\nf = io.FileIO('data.bin', b'rb')  # TypeError: invalid mode: b'rb'\n\n# after\nf = io.FileIO('data.bin', 'rb')","handlingStrategy":"type-guard","validationCode":"if not isinstance(mode, str):\n    raise TypeError(f'mode must be str, got {type(mode).__name__}')\nf = io.FileIO(path, mode)","typeGuard":"def is_mode_str(m):\n    return isinstance(m, str) and len(m) > 0","tryCatchPattern":"try:\n    f = io.FileIO(path, mode)\nexcept TypeError as e:\n    if 'invalid mode' in str(e):\n        f = io.FileIO(path, str(mode))\n    else:\n        raise","preventionTips":["Keep modes as plain string literals or typed constants","Coerce config-loaded modes: mode = str(mode).strip()","Lint for positional-argument swaps when mode comes from a variable"],"tags":["python","io","file-io","mode","typeerror"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}