Understanding Python sys.flags for Runtime Options

Python's sys.flags struct sequence provides programmatic, read-only access to the command-line flags and runtime environment variables passed to the interpreter upon startup. This article explains how sys.flags works, breaks down the key interpreter options it exposes, and demonstrates how to inspect these runtime configurations inside your Python scripts.

What Is sys.flags?

When the Python interpreter initializes, it parses command-line arguments (such as -O, -v, or -B) and runtime environment variables (such as PYTHONOPTIMIZE or PYTHONDONTWRITEBYTECODE). The resulting state of these interpreter configurations is stored in sys.flags, which is an instance of a read-only structseq (a named tuple-like object) defined in the standard sys module.

Each attribute in sys.flags corresponds to a specific flag or setting. The attributes are integers, usually representing either a boolean state (0 for disabled, 1 for enabled) or an integer level representing how many times a flag was passed.

Accessing sys.flags

You can inspect the entire structure or access individual fields directly:

import sys

# View all flags and their current values
print(sys.flags)

# Access a specific flag
print("Optimization level:", sys.flags.optimize)
print("Bytecode suppression:", sys.flags.dont_write_bytecode)

If you start Python with python -O -B script.py, sys.flags.optimize will return 1, and sys.flags.dont_write_bytecode will return 1.

Common Attributes Exposed by sys.flags

Here are the primary attributes provided by sys.flags and what they reveal about the execution environment:

Practical Use Cases

Relying on sys.flags allows scripts and libraries to adapt dynamically to their execution environment:

  1. Conditional Logic Based on Optimization: Library authors can verify if sys.flags.optimize == 2 before relying on __doc__ attributes at runtime, preventing errors caused by stripped docstrings.
  2. Security and Isolation Audits: Diagnostic utilities can verify that sys.flags.isolated or sys.flags.ignore_environment is set to ensure reproducible and secure execution in production containers.
  3. Debug Tooling: Developer tools can check sys.flags.dev_mode to automatically enable extra runtime checks and warnings without requiring separate configuration files.