How Python stat.S_ISDIR Checks os.stat Mode Bits
When inspecting files in Python, calling os.stat()
returns a stat_result object containing the
st_mode attribute, an integer that encodes both file
permissions and file type flags. The stat.S_ISDIR()
function evaluates this integer using bitwise operations to isolate the
file type bits from permission bits and checks whether they match the
directory constant. This article explains the internal bitwise logic,
the underlying POSIX constants, and how the integer values are filtered
and evaluated.
Understanding
st_mode Integer Encoding
The st_mode field is typically a 16-bit integer adhering
to POSIX standards. This integer encodes multiple pieces of information
into distinct bit ranges:
- Bits 0–11: Permissions (read, write, execute for user, group, and others) as well as special flags (setuid, setgid, sticky bit).
- Bits 12–15: The file type mask (specifying whether the entry is a regular file, directory, symbolic link, socket, FIFO, or character/block device).
Because file permissions change dynamically without altering the file's fundamental type, the permissions portion must be cleared before identifying the file type.
The Bitwise Mask and Directory Constant
Python's stat module defines specific constants
representing these bit patterns:
stat.S_IFMT(0o170000or0xF000/61440in decimal): The bitmask used to clear permission flags and retain only the file type bits.stat.S_IFDIR(0o040000or0x4000/16384in decimal): The specific bit pattern designated for directories.
How
stat.S_ISDIR() Evaluates the Integer
Internally, stat.S_ISDIR(mode) is implemented as a
simple bitwise expression:
def S_ISDIR(mode):
return (mode & 0o170000) == 0o040000Or, using the module's constants:
def S_ISDIR(mode):
return (mode & stat.S_IFMT) == stat.S_IFDIRThe evaluation follows two steps:
- Bitwise AND (
mode & stat.S_IFMT): The bitwise AND operation applies the mask0o170000to the inputmode. Any bits corresponding to permissions (bits 0–11) become0, while the file type bits (bits 12–15) remain unchanged. - Equality Comparison (
== stat.S_IFDIR): The isolated file type bits are compared directly to0o040000. If the isolated bits match0o040000, the function evaluates toTrue. If the target is a regular file (0o100000), a symlink (0o120000), or any other type, the comparison returnsFalse.
Practical Walkthrough
Consider a directory with standard 0o755
(rwxr-xr-x) permissions:
- In octal, its full
st_modevalue is0o040755(decimal16877). - Applying the mask:
0o040755 & 0o170000yields0o040000. - Evaluating equality:
0o040000 == 0o040000producesTrue.
If the entry were a regular script with the same permissions
(0o100755):
- Applying the mask:
0o100755 & 0o170000yields0o100000(stat.S_IFREG). - Evaluating equality:
0o100000 == 0o040000producesFalse.
By using this bitwise masking process, stat.S_ISDIR()
reliably determines if a path is a directory regardless of the read,
write, or execute permissions assigned to it.