[torchgen] Refactor and simplify gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)#150727
[torchgen] Refactor and simplify gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)#150727XuehaiPan wants to merge 22 commits intogh/XuehaiPan/264/basefrom
gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)#150727Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/150727
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ✅ You can merge normally! (1 Unrelated Failure)As of commit c49612e with merge base e2ce17c ( UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)
There was a problem hiding this comment.
Copilot reviewed 3 out of 4 changed files in this pull request and generated no comments.
Files not reviewed (1)
- torch/_C/return_types.pyi.in: Language not supported
Comments suppressed due to low confidence (1)
torch/_subclasses/fake_tensor.py:1021
- Using 'type: ignore[assignment]' suppresses potential type mismatches between the return type of suggest_memory_format and the expected type. Consider either updating the return type of suggest_memory_format or explicitly casting memory_format to ensure type consistency.
memory_format = None # type: ignore[assignment]
| def format_function_signature( | ||
| name: str, arguments: Iterable[str] = (), return_type: str | None = None | ||
| ) -> str: | ||
| if not isinstance(arguments, (list, tuple)): | ||
| arguments = tuple(arguments) | ||
| return_type = f" -> {return_type}" if return_type is not None else "" | ||
|
|
||
| sig = f"def {name}({', '.join(arguments)}){return_type}: ..." | ||
| if len(sig) <= 80 or len(arguments) == 0 or tuple(arguments) == ("self",): | ||
| return sig | ||
|
|
||
| return "\n".join( | ||
| ( | ||
| f"def {name}(", | ||
| *(f" {arg}," for arg in arguments), | ||
| f"){return_type}: ...", | ||
| ) | ||
| ) |
There was a problem hiding this comment.
This PR provides a standard way to create a formatted signature. Previously, we did it in a handcrafted way.
…s (PEP 585) and Union Type (PEP 604) ghstack-source-id: 2b00421 Pull Request resolved: pytorch#150727
…s (PEP 585) and Union Type (PEP 604) ghstack-source-id: 312b22a Pull Request resolved: pytorch#150727
…s (PEP 585) and Union Type (PEP 604) ghstack-source-id: 87a2ba3 Pull Request resolved: pytorch#150727
aorenste
left a comment
There was a problem hiding this comment.
Unfortunately PEP604 is python 3.10+ and we have to support python 3.9 - so we can't convert to it yet.
It's safe to use PEP604 because pyi stub files are not runnable at runtime. In |
That's a good point. |
aorenste
left a comment
There was a problem hiding this comment.
n.b.: I spot-checked the diff in the output .pyi files and they look reasonable as well.
|
|
||
| At the moment, this module only handles type stubs for torch and | ||
| torch.Tensor. It should eventually be expanded to cover all functions | ||
| which come are autogenerated. |
There was a problem hiding this comment.
nit (I know this is just moved from below - but might as well fix if you have to update a new version):
| which come are autogenerated. | |
| which are autogenerated. |
| Extract the TensorMetadata of a tensor. | ||
| """ | ||
| memory_format: Optional[torch.memory_format] = suggest_memory_format(t) | ||
| memory_format = suggest_memory_format(t) |
There was a problem hiding this comment.
Why this change? It seems that memory_format can validly be None and it also seems unrelated to the rest of this PR...
| ) -> str: | ||
| if not isinstance(arguments, (list, tuple)): | ||
| arguments = tuple(arguments) | ||
| return_type = f" -> {return_type}" if return_type is not None else "" |
There was a problem hiding this comment.
Does return_type is None mean "unknown return type" or "returns None"? It seems to be the former - because here if it's None I think it's implicitly Any (because it's missing)... Maybe a quick comment to clarify.
…s (PEP 585) and Union Type (PEP 604) ghstack-source-id: e9a854c Pull Request resolved: pytorch#150727
|
Starting merge as part of PR stack under #150728 |
…nd Union Type (PEP 604) (#150728) #129001 (comment) is the motivation for the whole stack of PRs. In `torch/__init__.py`, `torch._C.Type` shadows `from typing import Type`, and there is no type stub for `torch._C.Type` in `torch/_C/__init__.pyi`. So we need to use `from typing import Type as _Type`. After enabling [Generic TypeAlias (PEP 585)](https://peps.python.org/pep-0585) in the `.pyi` type stub files, we can use `type` instead of `typing.Type` or `from typing import Type as _Type`. ------ - [Generic TypeAlias (PEP 585)](https://peps.python.org/pep-0585): e.g. `typing.List[T] -> list[T]`, `typing.Dict[KT, VT] -> dict[KT, VT]`, `typing.Type[T] -> type[T]`. - [Union Type (PEP 604)](https://peps.python.org/pep-0604): e.g. `Union[X, Y] -> X | Y`, `Optional[X] -> X | None`, `Optional[Union[X, Y]] -> X | Y | None`. Note that in `.pyi` stub files, we do not need `from __future__ import annotations`. So this PR does not violate issue #117449: - #117449 ------ Pull Request resolved: #150728 Approved by: https://github.com/cyyever, https://github.com/aorenste ghstack dependencies: #150726, #150727
#129001 (comment) is the motivation for the whole stack of PRs. In
torch/__init__.py,torch._C.Typeshadowsfrom typing import Type, and there is no type stub fortorch._C.Typeintorch/_C/__init__.pyi. So we need to usefrom typing import Type as _Type. After enabling Generic TypeAlias (PEP 585) in the.pyitype stub files, we can usetypeinstead oftyping.Typeorfrom typing import Type as _Type.typing.List[T] -> list[T],typing.Dict[KT, VT] -> dict[KT, VT],typing.Type[T] -> type[T].Union[X, Y] -> X | Y,Optional[X] -> X | None,Optional[Union[X, Y]] -> X | Y | None.Note that in
.pyistub files, we do not needfrom __future__ import annotations. So this PR does not violate issue #117449:Stack from ghstack (oldest at bottom):
lintrunneron generated.pyistub files #150732.pyistub files #150731gen_pyiare properly formatted #150730torch/utils/data/datapipes/gen_pyi.pywithtorchgen#150626__all__totorch/nn/functional.pyiandtorch/return_types.pyi#150729.pyistub template to use Generic TypeAlias (PEP 585) and Union Type (PEP 604) #150728gen_pyi.pyto use Generic TypeAlias (PEP 585) and Union Type (PEP 604) #150727torchgen.utils.FileManagerto acceptpathlib.Path#150726cc @ezyang @malfet @xuzhao9 @gramster @bhosmer @bdhirsh @kadeng