Full name: stat: named after the Unix system call stat, which returns the status information that the operating system keeps about a file.
Definition
The stat module is the Python §12.23 standard-library module that decodes the status information an operating system keeps about a file. Three functions in Python’s os module fetch it: os.stat for a path, following any symbolic link §13.10 (a small file that holds another path) to the object it leads to; os.lstat for a path, describing a symbolic link itself; and os.fstat for an open file. Each returns a record whose st_mode field packs the file type and the permission bits into one integer. The stat module separates them.
The idea
A program is asked to read uploads/report and to refuse anything that is not an ordinary file. It calls os.stat, and the record says: regular file, 6 bytes, readable and writable by its owner. But report is a symbolic link, created by whoever filled the uploads directory, and it leads to a file outside that directory. os.stat did not lie. Following links is its job, so it described the object at the end of the link. Whether the name report is itself a link is a question about a different object, and only os.lstat answers it.
Two ideas make the module easy to use. First, every status call describes exactly one object, and the caller chooses which: the object at the end of all links, the link itself, or the file behind an open descriptor. Second, st_mode is two fields stored in one integer: its high bits say what kind of object it is, and its low bits say who may read, write or execute it. The stat module names the masks and tests for both fields, so a program writes stat.S_ISLNK(mode), not a bare number such as 0o120000.
How it works
Numbers in this entry that start with 0o are octal, as in Python source code: base 8, so each digit stands for exactly 3 bits. For example, 0o644 is .
Choose the object.
os.stat(path)looks the path up, follows every symbolic link on the way, including one in the last component, and describes the object it reaches.os.lstat(path), the same asos.stat(path, follow_symlinks=False), still follows links in the directory part of the path but stops at the last component: if that component is a symbolic link, the link itself is described.os.fstat(fd)takes a file descriptor §15.21, the small integer that the operating system gives a program for a file it has opened, and describes the object behind it without looking up any name.Read the record. Each call returns an
os.stat_resultwith these fields, among others:st_mode: the file type and the permission bits;st_ino: the inode number, the number by which the file system identifies the object;st_dev: the identifier of the device, meaning the file system, that holds the object;st_nlink: the number of hard links, meaning directory entries, that name the object;st_size: the size in bytes; for a symbolic link, the length of the path stored in it.
The record also holds the owner, the group and timestamps.
Decode the type.
stat.S_IFMT(mode)keeps only the type bits,mode & 0o170000. The result equals one of these constants:S_IFREG(0o100000, regular file),S_IFDIR(0o040000, directory),S_IFLNK(0o120000, symbolic link),S_IFCHRorS_IFBLK(character or block device, through which programs reach hardware),S_IFIFO(named pipe, a first-in, first-out §14.14 channel between programs) orS_IFSOCK(socket, an endpoint for communication between programs). The testsS_ISREG,S_ISDIR,S_ISLNKand their siblings make this comparison and returnTrueorFalse.Decode the permissions.
stat.S_IMODE(mode)keeps the low 12 bits,mode & 0o7777. Nine of them are the read, write and execute bits for the owner, the group and everyone else;S_IRUSR, for example, is0o400, read permission for the owner. The other three are the set-user-ID, set-group-ID and sticky bits.stat.filemode(mode)prints the whole mode the way thels -lcommand does, for example-rw-r--r--.
Worked example
On Linux, a directory holds a regular file notes.txt, which contains the 6 bytes hello and a newline and has the permissions 0o644, and a symbolic link latest whose content is the 9-character path notes.txt.
os.stat("latest") follows the link. Its st_mode is 33188, which in octal is 0o100644: . The type bits are 0o100644 & 0o170000 = 0o100000, which is S_IFREG, so S_ISREG returns True. The permission bits are 0o644: read and write for the owner (0o400 + 0o200), read for the group (0o040) and read for others (0o004), printed as -rw-r--r--. st_size is 6. The pair (st_dev, st_ino) equals that of os.stat("notes.txt"): both calls describe the same object.
os.lstat("latest") stops at the link. Its st_mode is 41471, which is 0o120777: . The type bits are 0o120000, which is S_IFLNK, so S_ISLNK returns True and S_ISREG returns False. The permission bits are 0o777, printed as lrwxrwxrwx. Linux gives every symbolic link these bits and ignores them; access is checked on the target. st_size is 9, the length of the stored path notes.txt, and st_ino is the link’s own inode number, which differs from the file’s.
Now delete the file notes.txt. The call os.stat("latest") then raises the exception FileNotFoundError, and the function os.path.exists, which follows links, returns False for latest although that name is still there. os.lstat("latest") still returns the link’s record, and os.path.lexists("latest") returns True.
Stated precisely
Let be a path whose last component names a symbolic link , and let be the object reached by following , through further links if leads to one. Then:
os.lstat(p)describes .S_ISLNK(st_mode)is true, (st_dev,st_ino) identifies , andst_sizeis the length in bytes of the path stored in , as POSIX (Portable Operating System Interface, the standard for Unix-like systems) requires.os.stat(p)describes , with the same (st_dev,st_ino) asos.statof any other path that leads to . Its type is never symbolic link. It fails, raisingFileNotFoundError, if does not exist, and fails with the error codeELOOPif resolution meets a loop or more links than the system allows; Linux follows at most 40 in one lookup.os.lstat(p)succeeds in both cases.If the last component of is not a symbolic link, both calls describe the same object. Both calls follow links in the directory part of .
For any st_mode value , the file type is bitwise AND 0o170000, and the permission and special bits are bitwise AND 0o7777. Bitwise AND §4.50 keeps a bit only where both numbers have a 1.
A record describes the chosen object at the moment of the call. Acting on it later assumes two things: the action reaches the same object, and the checked properties have not changed since the call. A path does not ensure the first, because the name can be repointed in between; an open descriptor does, because reads and writes through it reach the object that os.fstat described.
Limits and common mistakes
Checking a path and then opening it is a time-of-check to time-of-use §9.26 (TOCTOU) race condition §9.2. Between os.lstat and open, anyone who can write to the directory can replace the file with a symbolic link. The repair is to open first and check the open file: open with the flag O_NOFOLLOW, which makes the open fail if the last component is a symbolic link, call os.fstat on the descriptor, and decide on that record. To tie an earlier os.lstat result to the opened file, compare its (st_dev, st_ino) with those from os.fstat.
os.lstat protects only the last component. os.lstat("uploads/report") reports that report is not a link even when uploads is a symbolic link to some other directory.
Python’s convenience functions differ in the same way. These follow links: os.path.exists, os.path.isfile, os.path.isdir and the method Path.is_file of pathlib. These do not: os.path.islink, os.path.lexists and the method Path.is_symlink. A link whose target is missing therefore makes os.path.exists report a taken name as free.
Not a link does not mean a regular file. A named pipe or a device file is not a link either, and reading one can block forever or return data without end. Test S_ISREG when a regular file is required.
File metadata §13.11 is not content, and permission bits are not a decision. Equal type, size and modification time do not prove equal bytes; only comparing or hashing the content does. Permission bits say what the operating system enforces for each user, not whether a program should act on the file. The superuser, the administrator account (named root on Unix), bypasses most of them, and access control lists, which some file systems keep beside the mode, do not appear in st_mode.
The identity (st_dev, st_ino) is unique only among objects that exist at the same time. After a file is deleted, the file system may give its inode number to a new file; this is inode reuse §15.24.
Questions answered
How does lstat of a link differ from stat of its target?
lstat of a symbolic link describes the link itself, while stat of the same path follows the link and describes the object the link leads to. A symbolic link is a small file that holds a path. lstat reports the type symbolic link (S_ISLNK is true), the link’s own inode number (the number by which the file system identifies an object), a size equal to the length of the stored path, and, on Linux, permission bits 0o777 (octal 777: every permission for everyone) that are never used. stat reports the target’s type, for example regular file, and the target’s inode number, size, permissions, owner and times, exactly as stat of the target’s own name would.
For a link latest that holds the path notes.txt of a 6-byte regular file, stat gives the mode 0o100644 (regular file, permissions 0o644) and size 6, while lstat gives the mode 0o120777 (symbolic link) and size 9. Two further differences matter. If the target is missing, or the links form a loop, stat fails while lstat still succeeds. And only the last component of the path is affected: both calls follow links in the directory part. Both results describe one moment. To act safely on what was checked, open the file, with the flag O_NOFOLLOW if a link must be refused, and check the open file with fstat.
Related entries: File descriptor versus pathname (§15.21), Inode reuse (§15.24), File metadata versus content (§13.11), Hard link versus symbolic link (§13.10), O_NOFOLLOW and descriptor-relative access (§15.23), Time-of-check to time-of-use (TOCTOU) (§9.26). Further reading: [50].