feat: Refactor timeout handling in HTTPAdapter with new _prepare_timeout method
Summary
This PR refactors timeout handling in the HTTPAdapter class by extracting the timeout conversion logic into a dedicated _prepare_timeout method. This improves code organization, maintainability, and makes the timeout handling logic reusable for subclasses.
Changes Made
Code Refactoring
-
New Method: Added
_prepare_timeout()method toHTTPAdapterclass insrc/requests/adapters.py- Converts various timeout input formats (None, float, tuple, or TimeoutSauce) into a TimeoutSauce object
- Provides clear, documented interface for timeout handling
- Marked as internal API (not intended for direct user code usage) but exposed for subclass extensibility
-
Improved Error Handling: Enhanced timeout validation with exception chaining
- Uses
raise ... from excto preserve the original ValueError context - Provides more informative error messages when invalid timeout tuples are provided
- Maintains full exception traceback for debugging
- Uses
-
Code Simplification: Refactored the
send()method to use the new_prepare_timeout()method- Reduced code duplication
- Improved readability by separating concerns
- Changed from 13 lines of inline logic to a single method call
Testing
-
Comprehensive Test Coverage: Added 88 lines of tests in
tests/test_adapters.py- Tests valid timeout tuples with numeric values
- Tests tuples with None values
- Tests float timeout values
- Tests None timeout value
- Tests TimeoutSauce object passthrough
- Tests error cases: too many values, too few values, and empty tuples
- Verifies exception chaining is properly preserved
Files Changed
-
src/requests/adapters.py(+25, -13 lines) -
tests/test_adapters.py(+88 lines)
Benefits
- Better Code Organization: Timeout logic is now isolated in a dedicated method
-
Enhanced Extensibility: Subclasses can override
_prepare_timeout()for custom timeout handling - Improved Error Messages: Users get clearer feedback when providing invalid timeout values
- Better Debugging: Exception chaining preserves the full error context
- Increased Test Coverage: Comprehensive test suite ensures robust timeout handling
Backward Compatibility
✅ This change is fully backward compatible. The public API remains unchanged; this is purely an internal refactoring that improves code quality without affecting existing functionality.
I should add that this issue was found because of I think (I'm not 100% sure because everything was also typed according to mypy rules in the commit) pylint in https://github.com/psf/requests/pull/7054, if it was pylint that found this issue and it is a legitimate issue then it makes a strong case for the project to start using it imo.