Skip to content

Commit f15ddca

Browse files
author
hauntsaninja
committed
Check for PEP 604 usage in CI
Since this is a common review issue and our stubs have all been converted
1 parent 32a6257 commit f15ddca

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

.github/workflows/tests.yml

+8
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ jobs:
1717
- run: pip install toml
1818
- run: ./tests/check_consistent.py
1919

20+
pep-604:
21+
name: Check for PEP 604 usage
22+
runs-on: ubuntu-latest
23+
steps:
24+
- uses: actions/checkout@v2
25+
- uses: actions/setup-python@v2
26+
- run: ./tests/check_pep_604.py
27+
2028
flake8:
2129
name: Lint with flake8
2230
runs-on: ubuntu-latest

tests/check_pep_604.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env python3
2+
3+
import ast
4+
import sys
5+
from pathlib import Path
6+
7+
8+
def check_pep_604(tree: ast.AST, path: Path) -> list[str]:
9+
errors = []
10+
11+
class UnionFinder(ast.NodeVisitor):
12+
def visit_Subscript(self, node: ast.Subscript) -> None:
13+
if (
14+
isinstance(node.value, ast.Name)
15+
and "Union" in node.value.id.split(".")
16+
and isinstance(node.slice, ast.Tuple)
17+
):
18+
new_syntax = " | ".join(ast.unparse(x) for x in node.slice.elts)
19+
errors.append(
20+
(f"{path}:{node.lineno}: Use PEP 604 syntax for Unions, e.g. `{new_syntax}`")
21+
)
22+
23+
# This doesn't check type aliases (or type var bounds, etc), since those are not
24+
# currently supported
25+
class AnnotationFinder(ast.NodeVisitor):
26+
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
27+
UnionFinder().visit(node.annotation)
28+
29+
def visit_arg(self, node: ast.arg) -> None:
30+
if node.annotation is not None:
31+
UnionFinder().visit(node.annotation)
32+
33+
AnnotationFinder().visit(tree)
34+
return errors
35+
36+
37+
def main() -> None:
38+
errors = []
39+
for path in Path(".").glob("**/*.pyi"):
40+
if "@python2" in path.parts:
41+
continue
42+
if "stubs/protobuf/google/protobuf" in str(path): # TODO: fix protobuf stubs
43+
continue
44+
45+
with open(path) as f:
46+
tree = ast.parse(f.read())
47+
errors.extend(check_pep_604(tree, path))
48+
49+
if errors:
50+
print("\n".join(errors))
51+
sys.exit(1)
52+
53+
54+
if __name__ == "__main__":
55+
main()

0 commit comments

Comments
 (0)