Repository navigation
Expand file tree
/
Copy pathfix_type_hints.py
More file actions
71 lines (58 loc) · 2.55 KB
/
Copy pathfix_type_hints.py
File metadata and controls
71 lines (58 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python3
"""Fix Python 3.9 compatibility by replacing | union syntax with Union/Optional."""
import re
from pathlib import Path
def fix_file(filepath: Path) -> bool:
"""Fix type hints in a single file."""
content = filepath.read_text()
original = content
# Add Union import if needed
if ' | ' in content or ': str | ' in content or '-> str | ' in content:
if 'from typing import' in content:
# Add Union to existing import
content = re.sub(
r'from typing import ([^\n]+)',
lambda m: f"from typing import {m.group(1)}, Union" if 'Union' not in m.group(1) else m.group(0),
content
)
else:
# Add new import after docstring
lines = content.split('\n')
for i, line in enumerate(lines):
if line.startswith('"""') and i > 0:
# Find end of docstring
for j in range(i+1, len(lines)):
if '"""' in lines[j]:
lines.insert(j+2, '\nfrom typing import Union')
content = '\n'.join(lines)
break
break
# Replace | None with Optional (already imported)
content = re.sub(r': (\w+) \| None', r': Optional[\1]', content)
content = re.sub(r'-> (\w+) \| None', r'-> Optional[\1]', content)
# Replace complex types like dict[str, Any] | None
content = re.sub(r': (dict\[[\w\s,\[\]]+\]) \| None', r': Optional[\1]', content)
content = re.sub(r'-> (dict\[[\w\s,\[\]]+\]) \| None', r'-> Optional[\1]', content)
# Replace str | Path with Union[str, Path]
content = re.sub(r': str \| Path', r': Union[str, Path]', content)
content = re.sub(r'-> str \| Path', r'-> Union[str, Path]', content)
# Replace dict | None with Optional[dict]
content = re.sub(r': dict \| None', r': Optional[dict]', content)
content = re.sub(r'-> dict \| None', r'-> Optional[dict]', content)
if content != original:
filepath.write_text(content)
print(f"Fixed: {filepath}")
return True
return False
def main():
"""Fix all Python files in agentcoach package."""
fixed_count = 0
for filepath in Path('agentcoach').rglob('*.py'):
if fix_file(filepath):
fixed_count += 1
for filepath in Path('tests').rglob('*.py'):
if fix_file(filepath):
fixed_count += 1
print(f"\nFixed {fixed_count} files")
if __name__ == '__main__':
main()