Skip to content

Commit f8a656a

Browse files
committed
fix(tests): add Python 3.8-3.10 datetime.fromisoformat compatibility
Add datetime wrapper in tests/wire/__init__.py to handle 'Z' suffix for Python 3.8-3.10 compatibility. Python 3.10's datetime.fromisoformat() doesn't support 'Z' suffix (added in 3.11), so we convert 'Z' to '+00:00' automatically when the wire tests module is imported. This allows generated test files to use datetime.fromisoformat('2024-01-15T09:30:00Z') without modification, ensuring compatibility across all supported Python versions. The wrapper class inherits from the original datetime class, so all other datetime functionality remains unchanged.
1 parent f80076b commit f8a656a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

tests/wire/__init__.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Wire tests module.
3+
4+
This module patches datetime.fromisoformat() to handle 'Z' suffix for Python 3.10 compatibility.
5+
Python 3.10's datetime.fromisoformat() doesn't support 'Z' suffix (added in 3.11),
6+
so we convert 'Z' to '+00:00' automatically.
7+
8+
This uses a module-level import hook to intercept datetime imports.
9+
"""
10+
11+
import sys
12+
from datetime import datetime as _original_datetime
13+
14+
# Store original function
15+
_original_fromisoformat = _original_datetime.fromisoformat
16+
17+
18+
def _patched_fromisoformat(date_string: str) -> _original_datetime:
19+
"""Patched version that converts 'Z' to '+00:00' for Python 3.10 compatibility."""
20+
if date_string.endswith("Z"):
21+
date_string = date_string[:-1] + "+00:00"
22+
return _original_fromisoformat(date_string)
23+
24+
25+
# Create a wrapper datetime class that uses our patched fromisoformat
26+
class _DatetimeWrapper(_original_datetime):
27+
"""Wrapper class that patches fromisoformat for Python 3.10 compatibility."""
28+
29+
@staticmethod
30+
def fromisoformat(date_string: str) -> _original_datetime:
31+
"""Patched fromisoformat that handles 'Z' suffix."""
32+
return _patched_fromisoformat(date_string)
33+
34+
35+
# Replace datetime in the datetime module's __dict__ by creating a wrapper module
36+
# This intercepts imports of 'from datetime import datetime'
37+
_datetime_module = sys.modules["datetime"]
38+
_datetime_module.datetime = _DatetimeWrapper

0 commit comments

Comments
 (0)