reportOptionalContextManager.md

April 8, 2026 · View on GitHub

Overview

reportOptionalContextManager is a diagnostic in Pylance and Pyright that warns when you attempt to use a value that could be None as a context manager (e.g., in a with statement). This helps prevent runtime errors caused by trying to enter a context with an optional value.

Representative Issues

  • #4163: Ensure consistency in the use of type stubs between Pyright's CLI and Pylance settings, especially with useLibraryCodeForTypes.
  • #5200: Provide a configuration setting to allow users to customize diagnostic rule severities based on the type checking mode.
  • #79: Consider using Optional types in unions to manage None assignments more effectively.

Examples

from typing import Optional

file: Optional[open] = None

with file:  # Error: Object of type "None" cannot be used as context manager
    pass

Fix — check for None before using as context manager:

if file is not None:
    with file:
        pass

Common Fixes & Workarounds

  1. Use type guards (e.g., if resource is not None:) before using a possibly-optional value in a with statement.
  2. Add type annotations to clarify when a value can be None and handle those cases explicitly.
  3. Use assertions (e.g., assert resource is not None) before entering a context if you are certain the value is not None at that point.
  4. Adjust the diagnostic severity or disable the rule in your settings if needed. See the Pyright configuration documentation.

See Also