Coverage for mfutil/eval.py: 96%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-11-13 15:33 +0000

1import re 

2import fnmatch 

3import functools 

4import ast 

5import sys 

6 

7from simpleeval import EvalWithCompoundTypes, DEFAULT_FUNCTIONS 

8 

9fnmatch_fnmatch = fnmatch.fnmatch 

10re_match = functools.partial(re.match, flags=0) 

11re_imatch = functools.partial(re.match, flags=re.IGNORECASE) 

12 

13LOCAL_FUNCTIONS = { 

14 'fnmatch_fnmatch': fnmatch.fnmatch, 

15 're_match': re_match, 

16 're_imatch': re_imatch, 

17 'bool': bool 

18} 

19LOCAL_FUNCTIONS.update(DEFAULT_FUNCTIONS) 

20 

21 

22class _Eval(EvalWithCompoundTypes): 

23 

24 def __init__(self, operators=None, functions=None, names=None): 

25 super().__init__(operators, functions, names) 

26 

27 self.nodes.update({ 

28 ast.Constant: self._eval_bytes, 

29 }) 

30 

31 @staticmethod 

32 def _eval_bytes(node): 

33 return node.value 

34 

35def _partialclass(cls, *args, **kwargs): 

36 

37 class NewCls(cls): 

38 if sys.version_info.major >= 3: 

39 __init__ = functools.partialmethod(cls.__init__, *args, **kwargs) 

40 else: 

41 __init__ = functools.partial(cls.__init__, *args, **kwargs) 

42 

43 return NewCls 

44 

45 

46SandboxedEval = _partialclass(_Eval, functions=LOCAL_FUNCTIONS)