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:

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:

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) == 0o040000

Or, using the module's constants:

def S_ISDIR(mode):
    return (mode & stat.S_IFMT) == stat.S_IFDIR

The evaluation follows two steps:

  1. Bitwise AND (mode & stat.S_IFMT): The bitwise AND operation applies the mask 0o170000 to the input mode. Any bits corresponding to permissions (bits 0–11) become 0, while the file type bits (bits 12–15) remain unchanged.
  2. Equality Comparison (== stat.S_IFDIR): The isolated file type bits are compared directly to 0o040000. If the isolated bits match 0o040000, the function evaluates to True. If the target is a regular file (0o100000), a symlink (0o120000), or any other type, the comparison returns False.

Practical Walkthrough

Consider a directory with standard 0o755 (rwxr-xr-x) permissions:

If the entry were a regular script with the same permissions (0o100755):

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.