From 763ce08e6bd160ee2a1ebebecaa5a05ff50a5502 Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Sat, 20 May 2023 17:31:12 +0100 Subject: [PATCH 1/2] clinic.py: Modernise `parse_converter()` using pattern-matching --- Tools/clinic/clinic.py | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/Tools/clinic/clinic.py b/Tools/clinic/clinic.py index b00b480a684d80..0b9283cdeca80f 100755 --- a/Tools/clinic/clinic.py +++ b/Tools/clinic/clinic.py @@ -4906,22 +4906,27 @@ def bad_node(self, node): key = f"{parameter_name}_as_{c_name}" if c_name else parameter_name self.function.parameters[key] = p - def parse_converter(self, annotation): - if (isinstance(annotation, ast.Constant) and - type(annotation.value) is str): - return annotation.value, True, {} - - if isinstance(annotation, ast.Name): - return annotation.id, False, {} - - if not isinstance(annotation, ast.Call): - fail("Annotations must be either a name, a function call, or a string.") - - name = annotation.func.id - symbols = globals() - - kwargs = {node.arg: eval_ast_expr(node.value, symbols) for node in annotation.keywords} - return name, False, kwargs + KwargDict = dict[str | None, Any] + + def parse_converter( + self, annotation: ast.expr | None + ) -> tuple[str, bool, KwargDict]: + match annotation: + case ast.Constant(value=str() as value): + return value, True, {} + case ast.Name(name): + return name, False, {} + case ast.Call(func=ast.Name(name)): + symbols = globals() + kwargs = { + node.arg: eval_ast_expr(node.value, symbols) + for node in annotation.keywords + } + return name, False, kwargs + case _: + fail( + "Annotations must be either a name, a function call, or a string." + ) def parse_special_symbol(self, symbol): if symbol == '*': From 0baef8ca205f7000e721c84c1c79914c8e3e035a Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Sun, 21 May 2023 10:16:01 +0100 Subject: [PATCH 2/2] static method --- Tools/clinic/clinic.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Tools/clinic/clinic.py b/Tools/clinic/clinic.py index 0b9283cdeca80f..36c475e0fe6f76 100755 --- a/Tools/clinic/clinic.py +++ b/Tools/clinic/clinic.py @@ -4908,9 +4908,8 @@ def bad_node(self, node): KwargDict = dict[str | None, Any] - def parse_converter( - self, annotation: ast.expr | None - ) -> tuple[str, bool, KwargDict]: + @staticmethod + def parse_converter(annotation: ast.expr | None) -> tuple[str, bool, KwargDict]: match annotation: case ast.Constant(value=str() as value): return value, True, {}