{"record":{"id":"990e3663d802af6f","repo":"python/cpython","slug":"integer-argument-expected-got-float","errorCode":null,"errorMessage":"integer argument expected, got float","messagePattern":"integer argument expected, got float","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/_pyio.py","lineNumber":1546,"sourceCode":"        writing.\n\n        A custom opener can be used by passing a callable as *opener*.\n        The underlying file descriptor for the file object is then obtained\n        by calling opener with (*name*, *flags*).  *opener* must return\n        an open file descriptor (passing os.open as *opener* results in\n        functionality similar to passing None).\n        \"\"\"\n        if self._fd >= 0:\n            # Have to close the existing file first.\n            self._stat_atopen = None\n            try:\n                if self._closefd:\n                    os.close(self._fd)\n            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 '","sourceCodeStart":1528,"sourceCodeEnd":1564,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pyio.py#L1528-L1564","documentation":"Raised by FileIO.__init__ when the file argument is a float. Because bool is a subclass of int and floats are not accepted as file descriptors, the constructor explicitly rejects float before the int fd handling path (note the bool special case that only draws a RuntimeWarning, whereas float is a hard TypeError).","triggerScenarios":"open(3.0, 'rb') or io.FileIO(2.5); passing a value computed with float arithmetic (e.g. os.dup results passed through float(), or division like fd/1) where a file descriptor integer or a path was expected.","commonSituations":"fd variables accidentally converted to float by numeric pipelines (numpy scalars of dtype float are also rejected differently, but plain Python float hits this exact branch); typos where a path string was replaced by a numeric variable; JSON-parsed config in which the fd arrived as 3.0 instead of 3.","solutions":["Pass an int file descriptor or a str/bytes/os.PathLike path, never a float","Coerce numeric config values before use: fd = int(fd) after verifying it is integral","If the value is really a path, make sure it stays a string (check for accidental str(fd) vs fd mix-ups)"],"exampleFix":"# before\nfd = json_config['fd']  # arrived as 3.0\nf = open(fd, 'rb')  # TypeError: integer argument expected, got float\n\n# after\nfd = int(json_config['fd'])\nf = open(fd, 'rb')","handlingStrategy":"type-guard","validationCode":"import numbers\ndef normalize_fd(file):\n    if isinstance(file, float):\n        if file.is_integer():\n            return int(file)\n        raise TypeError('integer argument expected, got float')\n    return file\nf = open(normalize_fd(file_arg), 'rb')","typeGuard":"def is_fd_or_path(f):\n    return isinstance(f, (str, bytes, os.PathLike)) or (isinstance(f, int) and not isinstance(f, (bool, float)) and f >= 0)","tryCatchPattern":"try:\n    f = open(file_arg, 'rb')\nexcept TypeError as e:\n    if 'float' in str(e):\n        f = open(int(file_arg), 'rb')\n    else:\n        raise","preventionTips":["Keep fds as int; avoid float arithmetic on fd variables","Validate externally sourced fds (JSON/YAML) with isinstance(x, int)","Use None, not -1 or 0.0, as the 'no fd yet' sentinel"],"tags":["python","io","file-io","typeerror","file-descriptor"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}