Coverage for mfutil/eval.py: 96%

24 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-12-18 16:04 +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.Bytes: self._eval_bytes, 

29 }) 

30 

31 @staticmethod 

32 def _eval_bytes(node): 

33 return node.s 

34 

35 

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

37 

38 class NewCls(cls): 

39 if sys.version_info.major >= 3: 

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

41 else: 

42 # FIXME : this does not work with python2 

43 # We can't use functools.partial on __init__ function 

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

45 

46 return NewCls 

47 

48 

49SandboxedEval = _partialclass(_Eval, functions=LOCAL_FUNCTIONS)