Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tools.calculation: replace deprecated ast.Num with ast.Constant #2464

Merged
merged 2 commits into from
Aug 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions sopel/tools/calculation.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,28 +57,50 @@ def _eval_node(self, node, timeout):
A subclass could overwrite this to handle more nodes, calling it only
for nodes it does not implement itself.
"""
if isinstance(node, ast.Num):
return node.n
if isinstance(node, ast.Constant):
if not isinstance(node.value, (int, float)):
raise ExpressionEvaluator.Error(
"'{}' values are not supported".format(
type(node.value).__name__,
)
)

return node.value

elif isinstance(node, ast.BinOp):
if type(node.op) not in self.binary_ops:
raise ExpressionEvaluator.Error(
"Unsupported binary operator '{}'".format(
type(node.op).__name__,
)
)

elif (isinstance(node, ast.BinOp) and
type(node.op) in self.binary_ops):
left = self._eval_node(node.left, timeout)
right = self._eval_node(node.right, timeout)
if time.time() > timeout:
raise ExpressionEvaluator.Error(
"Time for evaluating expression ran out.")
return self.binary_ops[type(node.op)](left, right)

elif (isinstance(node, ast.UnaryOp) and
type(node.op) in self.unary_ops):
elif isinstance(node, ast.UnaryOp):
if type(node.op) not in self.unary_ops:
raise ExpressionEvaluator.Error(
"Unsupported unary operator '{}'".format(
type(node.op).__name__,
)
)

operand = self._eval_node(node.operand, timeout)
if time.time() > timeout:
raise ExpressionEvaluator.Error(
"Time for evaluating expression ran out.")
return self.unary_ops[type(node.op)](operand)

raise ExpressionEvaluator.Error(
"Ast.Node '%s' not implemented." % (type(node).__name__,))
"Node type '{}' is not supported.".format(
type(node).__name__,
)
)


def guarded_mul(left, right):
Expand Down