|
| 1 | +""" |
| 2 | +Check that pandas/core imports pandas.array as pd_array. |
| 3 | +
|
| 4 | +This makes it easier to grep for usage of pandas array. |
| 5 | +
|
| 6 | +This is meant to be run as a pre-commit hook - to run it manually, you can do: |
| 7 | +
|
| 8 | + pre-commit run use-pd_array-in-core --all-files |
| 9 | +
|
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import ast |
| 14 | +import sys |
| 15 | +from typing import ( |
| 16 | + Optional, |
| 17 | + Sequence, |
| 18 | +) |
| 19 | + |
| 20 | +ERROR_MESSAGE = ( |
| 21 | + "{path}:{lineno}:{col_offset}: " |
| 22 | + "Don't use pd.array in core, import array as pd_array instead\n" |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +class Visitor(ast.NodeVisitor): |
| 27 | + def __init__(self, path: str) -> None: |
| 28 | + self.path = path |
| 29 | + |
| 30 | + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: |
| 31 | + # If array has been imported from somewhere in pandas, |
| 32 | + # check it's aliased as pd_array. |
| 33 | + if ( |
| 34 | + node.module is not None |
| 35 | + and node.module.startswith("pandas") |
| 36 | + and any(i.name == "array" and i.asname != "pd_array" for i in node.names) |
| 37 | + ): |
| 38 | + msg = ERROR_MESSAGE.format( |
| 39 | + path=self.path, lineno=node.lineno, col_offset=node.col_offset |
| 40 | + ) |
| 41 | + sys.stdout.write(msg) |
| 42 | + sys.exit(1) |
| 43 | + super().generic_visit(node) |
| 44 | + |
| 45 | + def visit_Attribute(self, node: ast.Attribute) -> None: |
| 46 | + if ( |
| 47 | + isinstance(node.value, ast.Name) |
| 48 | + and node.value.id == "pd" |
| 49 | + and node.attr == "array" |
| 50 | + ): |
| 51 | + msg = ERROR_MESSAGE.format( |
| 52 | + path=self.path, lineno=node.lineno, col_offset=node.col_offset |
| 53 | + ) |
| 54 | + sys.stdout.write(msg) |
| 55 | + sys.exit(1) |
| 56 | + super().generic_visit(node) |
| 57 | + |
| 58 | + |
| 59 | +def use_pd_array(content: str, path: str) -> None: |
| 60 | + tree = ast.parse(content) |
| 61 | + visitor = Visitor(path) |
| 62 | + visitor.visit(tree) |
| 63 | + |
| 64 | + |
| 65 | +def main(argv: Optional[Sequence[str]] = None) -> None: |
| 66 | + parser = argparse.ArgumentParser() |
| 67 | + parser.add_argument("paths", nargs="*") |
| 68 | + args = parser.parse_args(argv) |
| 69 | + |
| 70 | + for path in args.paths: |
| 71 | + with open(path, encoding="utf-8") as fd: |
| 72 | + content = fd.read() |
| 73 | + use_pd_array(content, path) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + main() |
0 commit comments