1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
|
"""
SimpleEval - (C) 2013-2026 Daniel Fairhead
-------------------------------------
An short, easy to use, safe and reasonably extensible expression evaluator.
Designed for things like in a website where you want to allow the user to
generate a string, or a number from some other input, without allowing full
eval() or other unsafe or needlessly complex linguistics.
-------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-------------------------------------
Initial idea copied from J.F. Sebastian on Stack Overflow
( http://stackoverflow.com/a/9558001/1973500 ) with
modifications and many improvements.
-------------------------------------
Contributors:
- corro (Robin Baumgartner) (py3k)
- dratchkov (David R) (nested dicts)
- marky1991 (Mark Young) (slicing)
- T045T (Nils Berg) (!=, py3kstr, obj.
- perkinslr (Logan Perkins) (.__globals__ or .func_ breakouts)
- impala2 (Kirill Stepanov) (massive _eval refactor)
- gk (ugik) (Other iterables than str can DOS too, and can be made)
- daveisfera (Dave Johansen) 'not' Boolean op, Pycharm, pep8, various other fixes
- xaled (Khalid Grandi) method chaining correctly, double-eval bugfix.
- EdwardBetts (Edward Betts) spelling correction.
- charlax (Charles-Axel Dein charlax) Makefile and cleanups
- mommothazaz123 (Andrew Zhu) f"string" support, Python 3.8 support
- lubieowoce (Uryga) various potential vulnerabilities
- JCavallo (Jean Cavallo) names dict shouldn't be modified
- Birne94 (Daniel Birnstiel) for fixing leaking generators, star expressions
- patricksurry (Patrick Surry) or should return last value, even if falsy.
- shughes-uk (Samantha Hughes) python w/o 'site' should not fail to import.
- KOLANICH packaging / deployment / setup help & << + >> & other bit ops
- graingert (Thomas Grainger) packaging / deployment / setup help
- bozokopic (Bozo Kopic) Memory leak fix
- daxamin (Dax Amin) Better error for attempting to eval empty string
- smurfix (Matthias Urlichs) Allow clearing functions / operators / etc completely
- koenigsley (Mikhail Yeremeyev) documentation typos correction.
- kurtmckee (Kurt McKee) Infrastructure updates
- edgarrmondragon (Edgar Ramírez-Mondragón) Address Python 3.12+ deprecation warnings,
performance fixes
- cedk (Cédric Krier) <ced@b2ck.com> Allow running tests with Werror
- decorator-factory <decorator-factory@protonmail.com> More security fixes
- lkruitwagen (Lucas Kruitwagen) Adding support for dict comprehensions
- ByamB4 (Byambadalai) Reported breakout via module & disallowed functions as object attrs
-------------------------------------
Basic Usage:
>>> s = SimpleEval()
>>> s.eval("20 + 30")
50
You can add your own functions easily too:
if file.txt contents is "11"
>>> def get_file():
... with open("file.txt", 'r') as f:
... return f.read()
>>> s.functions["get_file"] = get_file
>>> s.eval("int(get_file()) + 31")
42
For more information, see the full package documentation on pypi, or the github
repo.
-----------
If you don't need to re-use the evaluator (with it's names, functions, etc),
then you can use the simple_eval() function:
>>> simple_eval("21 + 19")
40
You can pass names, operators and functions to the simple_eval function as
well:
>>> simple_eval("40 + two", names={"two": 2})
42
"""
import ast
import operator as op
import os
import sys
import types
import warnings
from random import random
from typing import Type, Dict, Set, Union
########################################
# Module wide 'globals'
MAX_STRING_LENGTH = 100000
MAX_COMPREHENSION_LENGTH = 10000
MAX_POWER = 4000000 # highest exponent
MAX_SHIFT = 10000 # highest << or >> (lshift / rshift)
MAX_SHIFT_BASE = int(sys.float_info.max) # highest on left side of << or >>
DISALLOW_PREFIXES = ["_", "func_"]
DISALLOW_METHODS = [
"format",
"format_map",
"mro",
"tb_frame",
"gi_frame",
"ag_frame",
"cr_frame",
"exec",
]
########################################
# Tiny helpers:
# Primitive types that are always safe: can't be modules, can't be in DISALLOW_FUNCTIONS,
# and don't need recursive container checks. Used as a fast path in _check_disallowed_items.
_PRIMITIVE_TYPES = frozenset({int, float, str, bool, type(None), bytes, complex})
# Disallow functions:
# This, strictly speaking, is not necessary. These /should/ never be accessible anyway,
# if DISALLOW_PREFIXES and DISALLOW_METHODS are all right. This is here to try and help
# people not be stupid. Allowing these functions opens up all sorts of holes - if any of
# their functionality is required, then please wrap them up in a safe container. And think
# very hard about it first. And don't say I didn't warn you.
# builtins is a dict in python >3.6 but a module before
DISALLOW_FUNCTIONS = {
type,
isinstance,
eval,
getattr,
setattr,
repr,
compile,
open,
exec,
globals,
locals,
os.popen,
os.system,
}
if hasattr(__builtins__, "help") or (
hasattr(__builtins__, "__contains__") and "help" in __builtins__ # type: ignore
):
# PyInstaller environment doesn't include this module.
DISALLOW_FUNCTIONS.add(help)
# Opt-in type safety experiment. Will be opt-out in 2.x
BASIC_ALLOWED_ATTRS: Dict[Union[Type, None], Set] = {
int: {
"as_integer_ratio",
"bit_length",
"conjugate",
"denominator",
"from_bytes",
"imag",
"numerator",
"real",
"to_bytes",
},
float: {
"as_integer_ratio",
"conjugate",
"fromhex",
"hex",
"imag",
"is_integer",
"real",
},
str: {
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
},
bool: {
"as_integer_ratio",
"bit_length",
"conjugate",
"denominator",
"from_bytes",
"imag",
"numerator",
"real",
"to_bytes",
},
None: set(),
dict: {
"clear",
"copy",
"fromkeys",
"get",
"items",
"keys",
"pop",
"popitem",
"setdefault",
"update",
"values",
},
list: {
"pop",
"append",
"index",
"reverse",
"count",
"sort",
"copy",
"extend",
"clear",
"insert",
"remove",
},
set: {
"pop",
"intersection_update",
"intersection",
"issubset",
"symmetric_difference_update",
"discard",
"isdisjoint",
"difference_update",
"issuperset",
"add",
"copy",
"union",
"clear",
"update",
"symmetric_difference",
"difference",
"remove",
},
tuple: {"index", "count"},
}
########################################
# Exceptions:
class TypeNotSpecified(Exception):
pass
class InvalidExpression(Exception):
"""Generic Exception"""
pass
class FunctionNotDefined(InvalidExpression):
"""sorry! That function isn't defined!"""
def __init__(self, func_name, expression):
self.message = "Function '{0}' not defined, for expression '{1}'.".format(
func_name, expression
)
setattr(self, "func_name", func_name) # bypass 2to3 confusion.
self.expression = expression
super(InvalidExpression, self).__init__(self.message)
class NameNotDefined(InvalidExpression):
"""a name isn't defined."""
def __init__(self, name, expression):
self.name = name
self.message = "'{0}' is not defined for expression '{1}'".format(name, expression)
self.expression = expression
super(InvalidExpression, self).__init__(self.message)
class AttributeDoesNotExist(InvalidExpression):
"""attribute does not exist"""
def __init__(self, attr, expression):
self.message = "Attribute '{0}' does not exist in expression '{1}'".format(
attr, expression
)
self.attr = attr
self.expression = expression
super(InvalidExpression, self).__init__(self.message)
class OperatorNotDefined(InvalidExpression):
"""operator does not exist"""
def __init__(self, attr, expression):
self.message = "Operator '{0}' does not exist in expression '{1}'".format(attr, expression)
self.attr = attr
self.expression = expression
super(InvalidExpression, self).__init__(self.message)
class FeatureNotAvailable(InvalidExpression):
"""What you're trying to do is not allowed."""
pass
class NumberTooHigh(InvalidExpression):
"""Sorry! That number is too high. I don't want to spend the
next 10 years evaluating this expression!"""
pass
class IterableTooLong(InvalidExpression):
"""That iterable is **way** too long, baby."""
pass
class AssignmentAttempted(UserWarning):
"""Assignment not allowed in SimpleEval"""
pass
class MultipleExpressions(UserWarning):
"""Only the first expression parsed will be used"""
pass
# Sentinal used during attr access
_ATTR_NOT_FOUND = object()
class ModuleWrapper:
"""Wraps a module to safely expose it in expressions.
By default, modules are not allowed in simpleeval names to prevent
accidental or malicious access to dangerous functions. ModuleWrapper
allows explicit opt-in to module access while still enforcing
restrictions on dangerous methods and functions.
Example:
>>> from simpleeval import SimpleEval, ModuleWrapper
>>> import os.path
>>> s = SimpleEval(names={'path': ModuleWrapper(os.path)})
>>> s.eval('path.exists("/etc/passwd")') # Works
"""
def __init__(self, module, allowed_attrs=None):
"""
Args:
module: The module to wrap
allowed_attrs: Optional set of allowed attribute names.
If None, all public attributes are allowed
(but still subject to DISALLOW_METHODS checks).
"""
if not isinstance(module, types.ModuleType):
raise TypeError(f"ModuleWrapper requires a module, got {type(module)}")
self._module = module
self._allowed_attrs = allowed_attrs
def __getattr__(self, name):
# Block private/magic attributes
if name.startswith("_"):
raise FeatureNotAvailable(f"Access to private attribute '{name}' is not allowed")
# Check if attribute is in disallowed methods list
if name in DISALLOW_METHODS:
raise FeatureNotAvailable(f"Method '{name}' is not allowed on modules")
# Check allowed_attrs whitelist if specified
if self._allowed_attrs is not None and name not in self._allowed_attrs:
raise FeatureNotAvailable(f"Access to '{name}' is not allowed on this wrapped module")
return getattr(self._module, name)
########################################
# Default simple functions to include:
def random_int(top):
"""return a random int below <top>"""
return int(random() * top)
def safe_power(a, b): # pylint: disable=invalid-name
"""a limited exponent/to-the-power-of function, for safety reasons"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise NumberTooHigh("Sorry! I don't want to evaluate {0} ** {1}".format(a, b))
return a**b
def safe_mult(a, b): # pylint: disable=invalid-name
"""limit the number of times an iterable can be repeated..."""
if hasattr(a, "__len__") and b * len(a) > MAX_STRING_LENGTH:
raise IterableTooLong("Sorry, I will not evaluate something that long.")
if hasattr(b, "__len__") and a * len(b) > MAX_STRING_LENGTH:
raise IterableTooLong("Sorry, I will not evaluate something that long.")
return a * b
def safe_add(a, b): # pylint: disable=invalid-name
"""iterable length limit again"""
if hasattr(a, "__len__") and hasattr(b, "__len__"):
if len(a) + len(b) > MAX_STRING_LENGTH:
raise IterableTooLong(
"Sorry, adding those two together would make something too long."
)
return a + b
def safe_rshift(a, b): # pylint: disable=invalid-name
"""rshift, but with input limits"""
if abs(b) > MAX_SHIFT or abs(a) > MAX_SHIFT_BASE:
raise NumberTooHigh("Sorry! I don't want to evaluate {0} >> {1}".format(a, b))
return a >> b
def safe_lshift(a, b): # pylint: disable=invalid-name
"""lshift, but with input limits"""
if abs(b) > MAX_SHIFT or abs(a) > MAX_SHIFT_BASE:
raise NumberTooHigh("Sorry! I don't want to evaluate {0} << {1}".format(a, b))
return a << b
########################################
# Defaults for the evaluator:
DEFAULT_OPERATORS = {
ast.Add: safe_add,
ast.Sub: op.sub,
ast.Mult: safe_mult,
ast.Div: op.truediv,
ast.FloorDiv: op.floordiv,
ast.RShift: safe_rshift,
ast.LShift: safe_lshift,
ast.Pow: safe_power,
ast.Mod: op.mod,
ast.Eq: op.eq,
ast.NotEq: op.ne,
ast.Gt: op.gt,
ast.Lt: op.lt,
ast.GtE: op.ge,
ast.LtE: op.le,
ast.Not: op.not_,
ast.USub: op.neg,
ast.UAdd: op.pos,
ast.BitXor: op.xor,
ast.BitOr: op.or_,
ast.BitAnd: op.and_,
ast.Invert: op.invert,
ast.In: lambda x, y: op.contains(y, x),
ast.NotIn: lambda x, y: not op.contains(y, x),
ast.Is: lambda x, y: x is y,
ast.IsNot: lambda x, y: x is not y,
}
DEFAULT_FUNCTIONS = {
"rand": random,
"randint": random_int,
"int": int,
"float": float,
"str": str,
}
DEFAULT_NAMES = {"True": True, "False": False, "None": None}
ATTR_INDEX_FALLBACK = True
########################################
# And the actual evaluator:
class SimpleEval(object): # pylint: disable=too-few-public-methods
"""A very simple expression parser.
>>> s = SimpleEval()
>>> s.eval("20 + 30 - ( 10 * 5)")
0
"""
expr = ""
def __init__(self, operators=None, functions=None, names=None, allowed_attrs=None):
"""
Create the evaluator instance. Set up valid operators (+,-, etc)
functions (add, random, get_val, whatever) and names."""
if operators is None:
operators = DEFAULT_OPERATORS.copy()
if functions is None:
functions = DEFAULT_FUNCTIONS.copy()
if names is None:
names = DEFAULT_NAMES.copy()
self.operators = operators
self.functions = functions
self.names = names
self.allowed_attrs = allowed_attrs
self.nodes = {
ast.Expr: self._eval_expr,
ast.Assign: self._eval_assign,
ast.AugAssign: self._eval_aug_assign,
ast.Import: self._eval_import,
ast.Name: self._eval_name,
ast.UnaryOp: self._eval_unaryop,
ast.BinOp: self._eval_binop,
ast.BoolOp: self._eval_boolop,
ast.Compare: self._eval_compare,
ast.IfExp: self._eval_ifexp,
ast.Call: self._eval_call,
ast.keyword: self._eval_keyword,
ast.Subscript: self._eval_subscript,
ast.Attribute: self._eval_attribute,
ast.Index: self._eval_index,
ast.Slice: self._eval_slice,
ast.JoinedStr: self._eval_joinedstr,
ast.FormattedValue: self._eval_formattedvalue,
ast.Constant: self._eval_constant,
}
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# py3.12 deprecated ast.Num, ast.Str, ast.NameConstant
# https://docs.python.org/3.12/whatsnew/3.12.html#deprecated
if Num := getattr(ast, "Num", None):
self.nodes[Num] = self._eval_num
if Str := getattr(ast, "Str", None):
self.nodes[Str] = self._eval_str
if NameConstant := getattr(ast, "NameConstant", None):
self.nodes[NameConstant] = self._eval_constant
# Defaults:
self.ATTR_INDEX_FALLBACK = ATTR_INDEX_FALLBACK
# Check for forbidden functions:
for f in self.functions.values():
if f in DISALLOW_FUNCTIONS:
raise FeatureNotAvailable("This function {} is a really bad idea.".format(f))
def __del__(self):
self.nodes = None
def _check_disallowed_items(self, item):
"""Check if item contains disallowed functions or modules.
Recursively checks containers (list, dict, tuple).
Raises FeatureNotAvailable if forbidden content found.
ModuleWrapper instances are allowed (explicit opt-in to module access).
"""
# Fast path: primitive scalars are always safe (most common case)
if type(item) in _PRIMITIVE_TYPES:
return
# Allow ModuleWrapper (explicit opt-in to module access)
if isinstance(item, ModuleWrapper):
return
if isinstance(item, types.ModuleType):
raise FeatureNotAvailable("Sorry, modules are not allowed")
if isinstance(item, (list, tuple)):
for element in item:
self._check_disallowed_items(element)
elif isinstance(item, dict):
for value in item.values():
self._check_disallowed_items(value)
elif callable(item) and item in DISALLOW_FUNCTIONS:
raise FeatureNotAvailable("This function is forbidden")
@staticmethod
def parse(expr):
"""parse an expression into a node tree"""
parsed = ast.parse(expr.strip())
if not parsed.body:
raise InvalidExpression("Sorry, cannot evaluate empty string")
if len(parsed.body) > 1:
warnings.warn(
"'{}' contains multiple expressions. Only the first will be used.".format(expr),
MultipleExpressions,
)
return parsed.body[0]
def eval(self, expr, previously_parsed=None):
"""evaluate an expression, using the operators, functions and
names previously set up."""
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
return self._eval(previously_parsed or self.parse(expr))
def _eval(self, node):
"""The internal evaluator used on each node in the parsed tree."""
try:
handler = self.nodes[type(node)]
except KeyError:
raise FeatureNotAvailable(
"Sorry, {0} is not available in this evaluator".format(type(node).__name__)
)
result = handler(node)
self._check_disallowed_items(result)
return result
def _eval_expr(self, node):
return self._eval(node.value)
def _eval_assign(self, node):
warnings.warn(
"Assignment ({}) attempted, but this is ignored".format(self.expr), AssignmentAttempted
)
return self._eval(node.value)
def _eval_aug_assign(self, node):
warnings.warn(
"Assignment ({}) attempted, but this is ignored".format(self.expr), AssignmentAttempted
)
return self._eval(node.value)
@staticmethod
def _eval_import(node):
raise FeatureNotAvailable("Sorry, 'import' is not allowed.")
@staticmethod
def _eval_num(node):
return node.n
@staticmethod
def _eval_str(node):
if len(node.s) > MAX_STRING_LENGTH:
raise IterableTooLong(
"String Literal in statement is too long! ({0}, when {1} is max)".format(
len(node.s), MAX_STRING_LENGTH
)
)
return node.s
@staticmethod
def _eval_constant(node):
if hasattr(node.value, "__len__") and len(node.value) > MAX_STRING_LENGTH:
raise IterableTooLong(
"Literal in statement is too long! ({0}, when {1} is max)".format(
len(node.value), MAX_STRING_LENGTH
)
)
return node.value
def _eval_unaryop(self, node):
try:
operator = self.operators[type(node.op)]
except KeyError:
raise OperatorNotDefined(node.op, self.expr)
return operator(self._eval(node.operand))
def _eval_binop(self, node):
try:
operator = self.operators[type(node.op)]
except KeyError:
raise OperatorNotDefined(node.op, self.expr)
return operator(self._eval(node.left), self._eval(node.right))
def _eval_boolop(self, node):
to_return = False
if isinstance(node.op, ast.And):
for value in node.values:
to_return = self._eval(value)
if not to_return:
break
elif isinstance(node.op, ast.Or):
for value in node.values:
to_return = self._eval(value)
if to_return:
break
return to_return
def _eval_compare(self, node):
right = self._eval(node.left)
to_return = True
for operation, comp in zip(node.ops, node.comparators):
if not to_return:
break
left = right
right = self._eval(comp)
to_return = self.operators[type(operation)](left, right)
return to_return
def _eval_ifexp(self, node):
return self._eval(node.body) if self._eval(node.test) else self._eval(node.orelse)
def _eval_call(self, node):
if isinstance(node.func, ast.Attribute):
func = self._eval(node.func)
else:
try:
func = self.functions[node.func.id]
except KeyError:
raise FunctionNotDefined(node.func.id, self.expr)
except AttributeError:
raise FeatureNotAvailable("Lambda Functions not implemented")
if func in DISALLOW_FUNCTIONS:
raise FeatureNotAvailable("This function is forbidden")
return func(
*(self._eval(a) for a in node.args), **dict(self._eval(k) for k in node.keywords)
)
def _eval_keyword(self, node):
return node.arg, self._eval(node.value)
def _eval_name(self, node):
try:
# This happens at least for slicing
# This is a safe thing to do because it is impossible
# that there is a true expression assigning to none
# (the compiler rejects it, so you can't even
# pass that to ast.parse)
return self.names[node.id]
except (TypeError, KeyError):
pass
if callable(self.names):
try:
return self.names(node)
except NameNotDefined:
pass
elif not hasattr(self.names, "__getitem__"):
raise InvalidExpression(
'Trying to use name (variable) "{0}" when no "names" defined for evaluator'.format(
node.id
)
)
if node.id in self.functions:
return self.functions[node.id]
raise NameNotDefined(node.id, self.expr)
def _eval_subscript(self, node):
container = self._eval(node.value)
key = self._eval(node.slice)
# Currently if there's a KeyError, that gets raised straight up.
# TODO: Should that be wrapped in an InvalidExpression?
return container[key]
def _eval_attribute(self, node):
# DISALLOW_PREFIXES & DISALLOW_METHODS are global, there's never any access to
# attrs with these names, so we can bail early:
for prefix in DISALLOW_PREFIXES:
if node.attr.startswith(prefix):
raise FeatureNotAvailable(
"Sorry, access to __attributes "
" or func_ attributes is not available. "
"({0})".format(node.attr)
)
if node.attr in DISALLOW_METHODS:
raise FeatureNotAvailable(
"Sorry, this method is not available. ({0})".format(node.attr)
)
# Evaluate "node" - the thing that we're trying to access an attr of first:
node_evaluated = self._eval(node.value)
# If we've opted in to the 'allowed_attrs' checking per type, then since we now
# know what kind of node we've got, we can check if we're permitted to access this
# attr name on this node:
if self.allowed_attrs is not None:
type_to_check = type(node_evaluated)
allowed_attrs = self.allowed_attrs.get(type_to_check, TypeNotSpecified)
if allowed_attrs == TypeNotSpecified:
raise FeatureNotAvailable(
f"Sorry, attribute access not allowed on '{type_to_check}'"
f" (attempted to access `.{node.attr}`)"
)
if node.attr not in allowed_attrs:
raise FeatureNotAvailable(
f"Sorry, '.{node.attr}' access not allowed on '{type_to_check}'"
)
item = _ATTR_NOT_FOUND
# Maybe the base object is an actual object, not just a dict
try:
item = getattr(node_evaluated, node.attr)
except (AttributeError, TypeError):
# TODO: is this a good idea? Try and look for [x] if .x doesn't work?
if self.ATTR_INDEX_FALLBACK:
try:
item = node_evaluated[node.attr]
except (KeyError, TypeError):
pass
if item is not _ATTR_NOT_FOUND:
if isinstance(item, types.ModuleType):
raise FeatureNotAvailable("Sorry, modules are not allowed in attribute access")
if callable(item) and item in DISALLOW_FUNCTIONS:
raise FeatureNotAvailable("This function is forbidden")
return item
# If it is neither, raise an exception
raise AttributeDoesNotExist(node.attr, self.expr)
def _eval_index(self, node):
return self._eval(node.value)
def _eval_slice(self, node):
lower = upper = step = None
if node.lower is not None:
lower = self._eval(node.lower)
if node.upper is not None:
upper = self._eval(node.upper)
if node.step is not None:
step = self._eval(node.step)
return slice(lower, upper, step)
def _eval_joinedstr(self, node):
length = 0
evaluated_values = []
for n in node.values:
val = str(self._eval(n))
if len(val) + length > MAX_STRING_LENGTH:
raise IterableTooLong("Sorry, I will not evaluate something this long.")
evaluated_values.append(val)
return "".join(evaluated_values)
def _eval_formattedvalue(self, node):
if node.format_spec:
fmt = "{:" + self._eval(node.format_spec) + "}"
return fmt.format(self._eval(node.value))
return self._eval(node.value)
class EvalWithCompoundTypes(SimpleEval):
"""
SimpleEval with additional Compound Types, and their respective
function editions. (list, tuple, dict, set).
"""
_max_count = 0
def __init__(self, operators=None, functions=None, names=None, allowed_attrs=None):
super(EvalWithCompoundTypes, self).__init__(operators, functions, names, allowed_attrs)
self.functions.update(list=list, tuple=tuple, dict=dict, set=set)
self.nodes.update(
{
ast.Dict: self._eval_dict,
ast.Tuple: self._eval_tuple,
ast.List: self._eval_list,
ast.Set: self._eval_set,
ast.ListComp: self._eval_comprehension,
ast.GeneratorExp: self._eval_comprehension,
ast.DictComp: self._eval_comprehension,
}
)
def eval(self, expr, previously_parsed=None):
# reset _max_count for each eval run
self._max_count = 0
return super(EvalWithCompoundTypes, self).eval(expr, previously_parsed)
def _eval_dict(self, node):
result = {}
for key, value in zip(node.keys, node.values):
if key is None:
# "{**x}" gets parsed as a key-value pair of (None, Name(x))
result.update(self._eval(value))
else:
result[self._eval(key)] = self._eval(value)
return result
def _eval_list(self, node):
result = []
for item in node.elts:
if isinstance(item, ast.Starred):
result.extend(self._eval(item.value))
else:
result.append(self._eval(item))
return result
def _eval_tuple(self, node):
return tuple(self._eval(x) for x in node.elts)
def _eval_set(self, node):
return set(self._eval(x) for x in node.elts)
def _eval_comprehension(self, node):
if isinstance(node, ast.DictComp):
to_return = {}
else:
to_return = []
extra_names = {}
previous_name_evaller = self.nodes[ast.Name]
def eval_names_extra(node):
"""
Here we hide our extra scope for within this comprehension
"""
if node.id in extra_names:
return extra_names[node.id]
return previous_name_evaller(node)
self.nodes.update({ast.Name: eval_names_extra})
def recurse_targets(target, value):
"""
Recursively (enter, (into, (nested, name), unpacking)) = \
and, (assign, (values, to), each
"""
if isinstance(target, ast.Name):
extra_names[target.id] = value
else:
for t, v in zip(target.elts, value):
recurse_targets(t, v)
def do_generator(gi=0):
g = node.generators[gi]
for i in self._eval(g.iter):
self._max_count += 1
if self._max_count > MAX_COMPREHENSION_LENGTH:
raise IterableTooLong("Comprehension generates too many elements")
recurse_targets(g.target, i)
if all(self._eval(iff) for iff in g.ifs):
if len(node.generators) > gi + 1:
do_generator(gi + 1)
else:
if isinstance(to_return, dict):
to_return[self._eval(node.key)] = self._eval(node.value)
elif isinstance(to_return, list):
to_return.append(self._eval(node.elt))
try:
do_generator()
finally:
self.nodes.update({ast.Name: previous_name_evaller})
return to_return
def simple_eval(expr, operators=None, functions=None, names=None, allowed_attrs=None):
"""Simply evaluate an expression"""
s = SimpleEval(
operators=operators,
functions=functions,
names=names,
allowed_attrs=allowed_attrs,
)
return s.eval(expr)
|