[Dynamo][Better Engineering] Add typing annotations to guard and source (#158397)

As part of better engineering week, we would like to improve out type support to improve dev experience in dynamo

This PR adds strict typing support to a critical set of files for dynamo, `source.py` and the base `_guards.py`

Running
```
mypy torch/_dynamo/source.py torch/_guards.py --linecount-report /tmp/coverage_log
```

| -------- | Lines Unannotated | Lines Total | % lines covered | Funcs Unannotated | Funcs Total | % funcs covered |
| -------- | ------- | -------- | ------- | ------- | ------- | ------- |
| Main  |  1227 | 2208 | 55.57% | 207 | 362 | 57.18% |
| This PR | 2217 | 2217 | 100.00% | 362 | 362 | 100.00% |
| Delta    | +990 | +9 | +44.43% | +155 | 0 | +42.82% |

Pull Request resolved: https://github.com/pytorch/pytorch/pull/158397
Approved by: https://github.com/anijain2305
This commit is contained in:
Lucas Kabela
2025-07-24 15:55:18 +00:00
committed by PyTorch MergeBot
parent fd48681b6a
commit abcb24f4de
22 changed files with 335 additions and 278 deletions

View File

@ -1065,7 +1065,7 @@ class GuardedCache(Generic[T]):
Helper to get the shape env from the tracing context.
"""
ctx = torch._guards.TracingContext.try_get()
if not ctx:
if not ctx or not ctx.fake_mode:
return None
return ctx.fake_mode.shape_env