Skip to content

Commit 6400736

Browse files
committed
config-able function blacklist
1 parent 6750243 commit 6400736

File tree

3 files changed

+19
-7
lines changed

3 files changed

+19
-7
lines changed

readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ A simple in game calculator plugin for [MCDReforged](https://github.com/Fallen-B
55

66
Requires [simpleeval](https://pypi.org/project/simpleeval/) module
77

8+
Configure file: `config/simple_calculator/config.json`
9+
810
## Usage
911

1012
It will calculate the expression with an extra prefix `==` such as `==1+1`. All unrelated chars will be ignored

simple_calculator/calculator.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,16 @@ def _calculate(self, expression: str) -> Optional[RESULT]:
4545

4646

4747
class SimpleevalCalculator(Calculator):
48-
def _calculate(self, expression: str) -> Optional[RESULT]:
48+
def __init__(self, config: Optional[Configure]):
49+
super().__init__(config)
50+
4951
def merge(a: dict, b: dict):
5052
ret = a.copy()
5153
ret.update(b)
5254
return ret
5355

5456
simpleeval.MAX_POWER = self.config.max_power_length
55-
s = simpleeval.SimpleEval(
57+
core = simpleeval.SimpleEval(
5658
operators=merge(simpleeval.DEFAULT_OPERATORS, {
5759
ast.BitXor: operator.xor,
5860
ast.BitAnd: operator.and_,
@@ -64,13 +66,16 @@ def merge(a: dict, b: dict):
6466
for k, v in math.__dict__.items():
6567
if not k.startswith('_'):
6668
if type(v) in [int, float]:
67-
s.names[k] = v
68-
elif callable(v) and k not in ['exp', 'expm1', 'ldexp', 'pow', 'factorial']:
69-
s.functions[k] = v
70-
s.functions.update({
69+
core.names[k] = v
70+
elif callable(v) and k not in self.config.function_blacklist:
71+
core.functions[k] = v
72+
core.functions.update({
7173
'hex': lambda x: hex(x).replace('0x', '', 1).rstrip('L').upper(),
7274
'bin': lambda x: bin(x).replace('0b', '', 1).rstrip('L'),
7375
'oct': lambda x: oct(x).replace('0o', '', 1).rstrip('L'),
7476
'bool': bool
7577
})
76-
return s.eval(expression)
78+
self.core = core
79+
80+
def _calculate(self, expression: str) -> Optional[RESULT]:
81+
return self.core.eval(expression)

simple_calculator/configure.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1+
from typing import List
2+
13
from mcdreforged.api.utils import Serializable
24

35

46
class Configure(Serializable):
57
max_result_length = 1000 # maximum result string length
68
max_power_length = 10000 # simpleeval.MAX_POWER override
79
enable_simpleeval = True # if enable simpleeval for better calculator if it's doable
10+
function_blacklist: List[str] = [
11+
'exp', 'expm1', 'ldexp', 'pow', 'factorial'
12+
]

0 commit comments

Comments
 (0)