From 95de4af8ce05a0772236a092e9a1f0ca25573190 Mon Sep 17 00:00:00 2001 From: Daniel Flook Date: Thu, 17 Oct 2024 11:34:58 +0100 Subject: [PATCH] Simplify is_constant_node --- src/python_minifier/module_printer.py | 2 +- src/python_minifier/util.py | 27 ++++++++++----------------- 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/src/python_minifier/module_printer.py b/src/python_minifier/module_printer.py index 70cf30c0..46a0ad3a 100644 --- a/src/python_minifier/module_printer.py +++ b/src/python_minifier/module_printer.py @@ -326,7 +326,7 @@ def visit_If(self, node, el=False): self._suite(node.orelse) def visit_For(self, node, is_async=False): - assert isinstance(node, ast.For) or (hasattr(ast, 'AsyncFor') and isinstance(node, ast.AsyncFor)) + assert isinstance(node, (ast.For, ast.AsyncFor)) self.printer.newline() diff --git a/src/python_minifier/util.py b/src/python_minifier/util.py index 1ec5c013..d6a59202 100644 --- a/src/python_minifier/util.py +++ b/src/python_minifier/util.py @@ -5,10 +5,9 @@ def is_constant_node(node, types): """ Is a node one of the specified node types - A node type may be an actual ast class, or a string naming one. - types is a single node type or an iterable of many. + A node type may be an actual ast class or a tuple of many. - If a node_type specified a specific Constant type (Str, Bytes, Num etc), + If types includes a specific Constant type (Str, Bytes, Num etc), returns true for Constant nodes of the correct type. :type node: ast.AST @@ -20,29 +19,23 @@ def is_constant_node(node, types): if not isinstance(types, tuple): types = (types,) - actual_types = [] for node_type in types: - if isinstance(node_type, str): - actual_type = getattr(ast, node_type, None) - if actual_type is not None: - actual_types.append(actual_type) - else: - actual_types.append(node_type) + assert not isinstance(node_type, str) - if isinstance(node, tuple(actual_types)): + if isinstance(node, types): return True - if hasattr(ast, 'Constant') and isinstance(node, ast.Constant): + if isinstance(node, ast.Constant): if type(node.value) in [type(None), type(True), type(False)]: - return ast.NameConstant in actual_types + return ast.NameConstant in types elif isinstance(node.value, (int, float, complex)): - return ast.Num in actual_types + return ast.Num in types elif isinstance(node.value, str): - return ast.Str in actual_types + return ast.Str in types elif isinstance(node.value, bytes): - return ast.Bytes in actual_types + return ast.Bytes in types elif node.value == Ellipsis: - return ast.Ellipsis in actual_types + return ast.Ellipsis in types else: raise RuntimeError('Unknown Constant value %r' % type(node.value))