Skip to content

Commit 95de4af

Browse files
committed
Simplify is_constant_node
1 parent cfc3a4b commit 95de4af

2 files changed

Lines changed: 11 additions & 18 deletions

File tree

src/python_minifier/module_printer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ def visit_If(self, node, el=False):
326326
self._suite(node.orelse)
327327

328328
def visit_For(self, node, is_async=False):
329-
assert isinstance(node, ast.For) or (hasattr(ast, 'AsyncFor') and isinstance(node, ast.AsyncFor))
329+
assert isinstance(node, (ast.For, ast.AsyncFor))
330330

331331
self.printer.newline()
332332

src/python_minifier/util.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ def is_constant_node(node, types):
55
"""
66
Is a node one of the specified node types
77
8-
A node type may be an actual ast class, or a string naming one.
9-
types is a single node type or an iterable of many.
8+
A node type may be an actual ast class or a tuple of many.
109
11-
If a node_type specified a specific Constant type (Str, Bytes, Num etc),
10+
If types includes a specific Constant type (Str, Bytes, Num etc),
1211
returns true for Constant nodes of the correct type.
1312
1413
:type node: ast.AST
@@ -20,29 +19,23 @@ def is_constant_node(node, types):
2019
if not isinstance(types, tuple):
2120
types = (types,)
2221

23-
actual_types = []
2422
for node_type in types:
25-
if isinstance(node_type, str):
26-
actual_type = getattr(ast, node_type, None)
27-
if actual_type is not None:
28-
actual_types.append(actual_type)
29-
else:
30-
actual_types.append(node_type)
23+
assert not isinstance(node_type, str)
3124

32-
if isinstance(node, tuple(actual_types)):
25+
if isinstance(node, types):
3326
return True
3427

35-
if hasattr(ast, 'Constant') and isinstance(node, ast.Constant):
28+
if isinstance(node, ast.Constant):
3629
if type(node.value) in [type(None), type(True), type(False)]:
37-
return ast.NameConstant in actual_types
30+
return ast.NameConstant in types
3831
elif isinstance(node.value, (int, float, complex)):
39-
return ast.Num in actual_types
32+
return ast.Num in types
4033
elif isinstance(node.value, str):
41-
return ast.Str in actual_types
34+
return ast.Str in types
4235
elif isinstance(node.value, bytes):
43-
return ast.Bytes in actual_types
36+
return ast.Bytes in types
4437
elif node.value == Ellipsis:
45-
return ast.Ellipsis in actual_types
38+
return ast.Ellipsis in types
4639
else:
4740
raise RuntimeError('Unknown Constant value %r' % type(node.value))
4841

0 commit comments

Comments
 (0)