Skip to content

fix(test.py): satisfy ty type checker on sys.stdout/stderr.reconfigure - #2544

Merged
zackees merged 1 commit into
masterfrom
fix/test-py-ty-reconfigure
May 29, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/test-py-ty-reconfigure

Conversation

@zackees

@zackees zackees commented May 29, 2026 •

Copy link
Copy Markdown
Member

Summary

The Stop hook's bash lint (which runs the Astral ty type checker) flagged two errors in test.py left by an earlier session:

test.py:44:9: error[unresolved-attribute] Attribute `reconfigure` is not defined on `TextIO` in union `TextIO | Any`
test.py:49:9: error[unresolved-attribute] Attribute `reconfigure` is not defined on `TextIO` in union `TextIO | Any`

reconfigure exists on io.TextIOWrapper (the concrete class) but not on the abstract TextIO type that sys.stdout/sys.stderr are declared as. The existing # type: ignore[union-attr] comment is mypy-syntax and isn't honored by ty.

Change

Use getattr(sys.std*, "reconfigure", None) + callable(...) — type-safe across mypy / pyright / ty without per-checker ignore comments. Drop the now-redundant AttributeError catch (the callable check makes it impossible). ValueError handling kept for invalid kwargs at runtime.

# Before
sys.stdout.reconfigure(line_buffering=True)  # type: ignore[union-attr]

# After
_reconfigure_stdout = getattr(sys.stdout, "reconfigure", None)
if callable(_reconfigure_stdout):
    try:
        _reconfigure_stdout(line_buffering=True)
    except ValueError:
        pass

Verification

  • bash lint — ty now passes (diagnostics count 8 → 6, remaining 6 are pre-existing os.system deprecation warnings in ci/ scripts, unrelated)
  • No behavior change — same line-buffering policy applied when stdout/stderr are piped

Summary by CodeRabbit

  • Bug Fixes
    • Improved robustness of output buffering initialization with a safer, more reliable configuration approach.

Review Change Stack

The Astral `ty` type checker (run via `bash lint`) doesn't honor the
existing `# type: ignore[union-attr]` mypy comment and flags both
`sys.stdout.reconfigure(...)` and `sys.stdout.reconfigure(...)` as
unresolved-attribute errors — `reconfigure` is on `io.TextIOWrapper`
but not the abstract `TextIO` type that `sys.stdout`/`sys.stderr` are
typed as.

Switch to `getattr(...,"reconfigure",None) + callable(...)` which is
type-safe across mypy / pyright / ty without per-checker ignore
comments, and remove the now-redundant `AttributeError` catch (the
`callable` check makes it impossible).

No behavior change — same line-buffering path, same `ValueError`
handling for invalid kwargs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

test.py replaces direct sys.stdout.reconfigure() and sys.stderr.reconfigure() calls with safer, type-agnostic logic that checks method availability via getattr and callable before setting line_buffering=True, and narrows exception handling from both AttributeError and ValueError to only ValueError.

Changes

Buffering Configuration Safety

Layer / File(s) Summary
Safe stdout/stderr buffering configuration
test.py
Lines 43–58 conditionally fetch the reconfigure method using getattr, verify it is callable, and apply line_buffering=True only when available, while suppressing only ValueError instead of both AttributeError and ValueError.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

A rabbit hops through buffering care,
With getattr checks both safe and fair,
No broad exceptions catch the day,
Just ValueError held at bay. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: refactoring sys.stdout/stderr.reconfigure calls to satisfy the ty type checker.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/test-py-ty-reconfigure

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test.py`:
- Around line 48-51: The try/except around the call to _reconfigure_stdout
should catch KeyboardInterrupt first and re-raise it, then handle ValueError;
update the block in test.py (the try that calls
_reconfigure_stdout(line_buffering=True)) to add an except KeyboardInterrupt:
raise before the existing except ValueError: pass, and make the identical change
for the other occurrence of the same pattern in the file (the similar try that
covers _reconfigure_stdout at the second location).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7b5e53c8-efd2-4d7e-b677-2e7831afc5d6

📥 Commits

Reviewing files that changed from the base of the PR and between 41cba7c and d0ccfee.

📒 Files selected for processing (1)
  • test.py

Comment thread test.py
Comment on lines +48 to +51
try:
_reconfigure_stdout(line_buffering=True)
except ValueError:
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle KeyboardInterrupt before other exceptions.

Both try-catch blocks violate the coding guideline requiring all try-catch blocks to handle KeyboardInterrupt before other exceptions. The guideline states: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions". This pattern is consistently followed throughout the codebase (see lines 205-210, 227-230, 257-259). As per coding guidelines, all Python try-catch blocks must handle KeyboardInterrupt before other exceptions.

🔧 Proposed fix to add KeyboardInterrupt handling
     if callable(_reconfigure_stdout):
         try:
             _reconfigure_stdout(line_buffering=True)
+        except KeyboardInterrupt:
+            raise
         except ValueError:
             pass
 if not sys.stderr.isatty():
     _reconfigure_stderr = getattr(sys.stderr, "reconfigure", None)
     if callable(_reconfigure_stderr):
         try:
             _reconfigure_stderr(line_buffering=True)
+        except KeyboardInterrupt:
+            raise
         except ValueError:
             pass

Also applies to: 55-58

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test.py` around lines 48 - 51, The try/except around the call to
_reconfigure_stdout should catch KeyboardInterrupt first and re-raise it, then
handle ValueError; update the block in test.py (the try that calls
_reconfigure_stdout(line_buffering=True)) to add an except KeyboardInterrupt:
raise before the existing except ValueError: pass, and make the identical change
for the other occurrence of the same pattern in the file (the similar try that
covers _reconfigure_stdout at the second location).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant