hotglue-singer-sdk 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. hotglue_singer_sdk/__init__.py +34 -0
  2. hotglue_singer_sdk/authenticators.py +554 -0
  3. hotglue_singer_sdk/cli/__init__.py +1 -0
  4. hotglue_singer_sdk/cli/common_options.py +37 -0
  5. hotglue_singer_sdk/configuration/__init__.py +1 -0
  6. hotglue_singer_sdk/configuration/_dict_config.py +101 -0
  7. hotglue_singer_sdk/exceptions.py +52 -0
  8. hotglue_singer_sdk/helpers/__init__.py +1 -0
  9. hotglue_singer_sdk/helpers/_catalog.py +122 -0
  10. hotglue_singer_sdk/helpers/_classproperty.py +18 -0
  11. hotglue_singer_sdk/helpers/_compat.py +15 -0
  12. hotglue_singer_sdk/helpers/_flattening.py +374 -0
  13. hotglue_singer_sdk/helpers/_schema.py +100 -0
  14. hotglue_singer_sdk/helpers/_secrets.py +41 -0
  15. hotglue_singer_sdk/helpers/_simpleeval.py +678 -0
  16. hotglue_singer_sdk/helpers/_singer.py +280 -0
  17. hotglue_singer_sdk/helpers/_state.py +282 -0
  18. hotglue_singer_sdk/helpers/_typing.py +231 -0
  19. hotglue_singer_sdk/helpers/_util.py +27 -0
  20. hotglue_singer_sdk/helpers/capabilities.py +240 -0
  21. hotglue_singer_sdk/helpers/jsonpath.py +39 -0
  22. hotglue_singer_sdk/io_base.py +134 -0
  23. hotglue_singer_sdk/mapper.py +691 -0
  24. hotglue_singer_sdk/mapper_base.py +156 -0
  25. hotglue_singer_sdk/plugin_base.py +415 -0
  26. hotglue_singer_sdk/py.typed +0 -0
  27. hotglue_singer_sdk/sinks/__init__.py +14 -0
  28. hotglue_singer_sdk/sinks/batch.py +90 -0
  29. hotglue_singer_sdk/sinks/core.py +412 -0
  30. hotglue_singer_sdk/sinks/record.py +66 -0
  31. hotglue_singer_sdk/sinks/sql.py +299 -0
  32. hotglue_singer_sdk/streams/__init__.py +14 -0
  33. hotglue_singer_sdk/streams/core.py +1294 -0
  34. hotglue_singer_sdk/streams/graphql.py +74 -0
  35. hotglue_singer_sdk/streams/rest.py +611 -0
  36. hotglue_singer_sdk/streams/sql.py +1023 -0
  37. hotglue_singer_sdk/tap_base.py +580 -0
  38. hotglue_singer_sdk/target_base.py +554 -0
  39. hotglue_singer_sdk/target_sdk/__init__.py +0 -0
  40. hotglue_singer_sdk/target_sdk/auth.py +124 -0
  41. hotglue_singer_sdk/target_sdk/client.py +286 -0
  42. hotglue_singer_sdk/target_sdk/common.py +13 -0
  43. hotglue_singer_sdk/target_sdk/lambda.py +121 -0
  44. hotglue_singer_sdk/target_sdk/rest.py +108 -0
  45. hotglue_singer_sdk/target_sdk/sinks.py +16 -0
  46. hotglue_singer_sdk/target_sdk/target.py +570 -0
  47. hotglue_singer_sdk/target_sdk/target_base.py +627 -0
  48. hotglue_singer_sdk/testing.py +198 -0
  49. hotglue_singer_sdk/typing.py +603 -0
  50. hotglue_singer_sdk-1.0.2.dist-info/METADATA +53 -0
  51. hotglue_singer_sdk-1.0.2.dist-info/RECORD +53 -0
  52. hotglue_singer_sdk-1.0.2.dist-info/WHEEL +4 -0
  53. hotglue_singer_sdk-1.0.2.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,678 @@
1
+ """
2
+ Simpleeval module originally imported on 2021-09-16 from:
3
+ - https://github.com/danthedeckie/simpleeval
4
+
5
+ For more information:
6
+ - https://gitlab.com/meltano/sdk/-/issues/213
7
+
8
+ -------------------------------------
9
+ SimpleEval - (C) 2013-2019 Daniel Fairhead
10
+ -------------------------------------
11
+
12
+ An short, easy to use, safe and reasonably extensible expression evaluator.
13
+ Designed for things like in a website where you want to allow the user to
14
+ generate a string, or a number from some other input, without allowing full
15
+ eval() or other unsafe or needlessly complex linguistics.
16
+
17
+ -------------------------------------
18
+
19
+ Permission is hereby granted, free of charge, to any person obtaining a copy
20
+ of this software and associated documentation files (the "Software"), to deal
21
+ in the Software without restriction, including without limitation the rights
22
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23
+ copies of the Software, and to permit persons to whom the Software is
24
+ furnished to do so, subject to the following conditions:
25
+
26
+ The above copyright notice and this permission notice shall be included in
27
+ all copies or substantial portions of the Software.
28
+
29
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35
+ THE SOFTWARE.
36
+
37
+ -------------------------------------
38
+
39
+ Initial idea copied from J.F. Sebastian on Stack Overflow
40
+ ( http://stackoverflow.com/a/9558001/1973500 ) with
41
+ modifications and many improvements.
42
+
43
+ -------------------------------------
44
+ Contributors:
45
+ - corro (Robin Baumgartner) (py3k)
46
+ - dratchkov (David R) (nested dicts)
47
+ - marky1991 (Mark Young) (slicing)
48
+ - T045T (Nils Berg) (!=, py3kstr, obj.
49
+ - perkinslr (Logan Perkins) (.__globals__ or .func_ breakouts)
50
+ - impala2 (Kirill Stepanov) (massive _eval refactor)
51
+ - gk (ugik) (Other iterables than str can DOS too, and can be made)
52
+ - daveisfera (Dave Johansen) 'not' Boolean op, Pycharm, pep8, various other fixes
53
+ - xaled (Khalid Grandi) method chaining correctly, double-eval bugfix.
54
+ - EdwardBetts (Edward Betts) spelling correction.
55
+ - charlax (Charles-Axel Dein charlax) Makefile and cleanups
56
+ - mommothazaz123 (Andrew Zhu) f"string" support, Python 3.8 support
57
+ - lubieowoce (Uryga) various potential vulnerabilities
58
+ - JCavallo (Jean Cavallo) names dict shouldn't be modified
59
+ - Birne94 (Daniel Birnstiel) for fixing leaking generators.
60
+ - patricksurry (Patrick Surry) or should return last value, even if falsy.
61
+ - shughes-uk (Samantha Hughes) python w/o 'site' should not fail to import.
62
+
63
+ -------------------------------------
64
+ Basic Usage:
65
+
66
+ >>> s = SimpleEval()
67
+ >>> s.eval("20 + 30")
68
+ 50
69
+
70
+ You can add your own functions easily too:
71
+
72
+ if file.txt contents is "11"
73
+
74
+ >>> def get_file():
75
+ ... with open("file.txt", 'r') as f:
76
+ ... return f.read()
77
+
78
+ >>> s.functions["get_file"] = get_file
79
+ >>> s.eval("int(get_file()) + 31")
80
+ 42
81
+
82
+ For more information, see the full package documentation on pypi, or the github
83
+ repo.
84
+
85
+ -----------
86
+
87
+ If you don't need to re-use the evaluator (with it's names, functions, etc),
88
+ then you can use the simple_eval() function:
89
+
90
+ >>> simple_eval("21 + 19")
91
+ 40
92
+
93
+ You can pass names, operators and functions to the simple_eval function as
94
+ well:
95
+
96
+ >>> simple_eval("40 + two", names={"two": 2})
97
+ 42
98
+
99
+ """
100
+ # flake8: noqa # Ignoring flake errors in imported module
101
+
102
+ import ast
103
+ import operator as op
104
+ import sys
105
+ import warnings
106
+ from random import random
107
+
108
+ PYTHON3 = sys.version_info[0] == 3
109
+
110
+ ########################################
111
+ # Module wide 'globals'
112
+
113
+ MAX_STRING_LENGTH = 100000
114
+ MAX_COMPREHENSION_LENGTH = 10000
115
+ MAX_POWER = 4000000 # highest exponent
116
+ DISALLOW_PREFIXES = ["_", "func_"]
117
+ DISALLOW_METHODS = ["format", "format_map", "mro"]
118
+
119
+ # Disallow functions:
120
+ # This, strictly speaking, is not necessary. These /should/ never be accessable anyway,
121
+ # if DISALLOW_PREFIXES and DISALLOW_METHODS are all right. This is here to try and help
122
+ # people not be stupid. Allowing these functions opens up all sorts of holes - if any of
123
+ # their functionality is required, then please wrap them up in a safe container. And think
124
+ # very hard about it first. And don't say I didn't warn you.
125
+ # builtins is a dict in python >3.6 but a module before
126
+ DISALLOW_FUNCTIONS = {type, isinstance, eval, getattr, setattr, repr, compile, open}
127
+ if hasattr(__builtins__, "help") or (
128
+ hasattr(__builtins__, "__contains__") and "help" in __builtins__ # type: ignore
129
+ ):
130
+ # PyInstaller environment doesn't include this module.
131
+ DISALLOW_FUNCTIONS.add(help)
132
+
133
+
134
+ if PYTHON3:
135
+ exec("DISALLOW_FUNCTIONS.add(exec)") # exec is not a function in Python2...
136
+
137
+
138
+ ########################################
139
+ # Exceptions:
140
+
141
+
142
+ class InvalidExpression(Exception):
143
+ """ Generic Exception """
144
+
145
+ pass
146
+
147
+
148
+ class FunctionNotDefined(InvalidExpression):
149
+ """ sorry! That function isn't defined! """
150
+
151
+ def __init__(self, func_name, expression):
152
+ self.message = "Function '{0}' not defined," " for expression '{1}'.".format(
153
+ func_name, expression
154
+ )
155
+ setattr(self, "func_name", func_name) # bypass 2to3 confusion.
156
+ self.expression = expression
157
+
158
+ # pylint: disable=bad-super-call
159
+ super(InvalidExpression, self).__init__(self.message)
160
+
161
+
162
+ class NameNotDefined(InvalidExpression):
163
+ """ a name isn't defined. """
164
+
165
+ def __init__(self, name, expression):
166
+ self.name = name
167
+ self.message = "'{0}' is not defined for expression '{1}'".format(
168
+ name, expression
169
+ )
170
+ self.expression = expression
171
+
172
+ # pylint: disable=bad-super-call
173
+ super(InvalidExpression, self).__init__(self.message)
174
+
175
+
176
+ class AttributeDoesNotExist(InvalidExpression):
177
+ """attribute does not exist"""
178
+
179
+ def __init__(self, attr, expression):
180
+ self.message = "Attribute '{0}' does not exist in expression '{1}'".format(
181
+ attr, expression
182
+ )
183
+ self.attr = attr
184
+ self.expression = expression
185
+
186
+
187
+ class FeatureNotAvailable(InvalidExpression):
188
+ """ What you're trying to do is not allowed. """
189
+
190
+ pass
191
+
192
+
193
+ class NumberTooHigh(InvalidExpression):
194
+ """Sorry! That number is too high. I don't want to spend the
195
+ next 10 years evaluating this expression!"""
196
+
197
+ pass
198
+
199
+
200
+ class IterableTooLong(InvalidExpression):
201
+ """ That iterable is **way** too long, baby. """
202
+
203
+ pass
204
+
205
+
206
+ class AssignmentAttempted(UserWarning):
207
+ pass
208
+
209
+
210
+ ########################################
211
+ # Default simple functions to include:
212
+
213
+
214
+ def random_int(top):
215
+ """ return a random int below <top> """
216
+
217
+ return int(random() * top)
218
+
219
+
220
+ def safe_power(a, b): # pylint: disable=invalid-name
221
+ """ a limited exponent/to-the-power-of function, for safety reasons """
222
+
223
+ if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
224
+ raise NumberTooHigh("Sorry! I don't want to evaluate {0} ** {1}".format(a, b))
225
+ return a ** b
226
+
227
+
228
+ def safe_mult(a, b): # pylint: disable=invalid-name
229
+ """ limit the number of times an iterable can be repeated... """
230
+
231
+ if hasattr(a, "__len__") and b * len(a) > MAX_STRING_LENGTH:
232
+ raise IterableTooLong("Sorry, I will not evalute something that long.")
233
+ if hasattr(b, "__len__") and a * len(b) > MAX_STRING_LENGTH:
234
+ raise IterableTooLong("Sorry, I will not evalute something that long.")
235
+
236
+ return a * b
237
+
238
+
239
+ def safe_add(a, b): # pylint: disable=invalid-name
240
+ """ iterable length limit again """
241
+
242
+ if hasattr(a, "__len__") and hasattr(b, "__len__"):
243
+ if len(a) + len(b) > MAX_STRING_LENGTH:
244
+ raise IterableTooLong(
245
+ "Sorry, adding those two together would" " make something too long."
246
+ )
247
+ return a + b
248
+
249
+
250
+ ########################################
251
+ # Defaults for the evaluator:
252
+
253
+ DEFAULT_OPERATORS = {
254
+ ast.Add: safe_add,
255
+ ast.Sub: op.sub,
256
+ ast.Mult: safe_mult,
257
+ ast.Div: op.truediv,
258
+ ast.FloorDiv: op.floordiv,
259
+ ast.Pow: safe_power,
260
+ ast.Mod: op.mod,
261
+ ast.Eq: op.eq,
262
+ ast.NotEq: op.ne,
263
+ ast.Gt: op.gt,
264
+ ast.Lt: op.lt,
265
+ ast.GtE: op.ge,
266
+ ast.LtE: op.le,
267
+ ast.Not: op.not_,
268
+ ast.USub: op.neg,
269
+ ast.UAdd: op.pos,
270
+ ast.In: lambda x, y: op.contains(y, x),
271
+ ast.NotIn: lambda x, y: not op.contains(y, x),
272
+ ast.Is: lambda x, y: x is y,
273
+ ast.IsNot: lambda x, y: x is not y,
274
+ }
275
+
276
+ DEFAULT_FUNCTIONS = {
277
+ "rand": random,
278
+ "randint": random_int,
279
+ "int": int,
280
+ "float": float,
281
+ "str": str if PYTHON3 else unicode, # type: ignore # 'unicode' not defined
282
+ }
283
+
284
+ DEFAULT_NAMES = {"True": True, "False": False, "None": None}
285
+
286
+ ATTR_INDEX_FALLBACK = True
287
+
288
+
289
+ ########################################
290
+ # And the actual evaluator:
291
+
292
+
293
+ class SimpleEval(object): # pylint: disable=too-few-public-methods
294
+ """A very simple expression parser.
295
+ >>> s = SimpleEval()
296
+ >>> s.eval("20 + 30 - ( 10 * 5)")
297
+ 0
298
+ """
299
+
300
+ expr = ""
301
+
302
+ def __init__(self, operators=None, functions=None, names=None):
303
+ """
304
+ Create the evaluator instance. Set up valid operators (+,-, etc)
305
+ functions (add, random, get_val, whatever) and names."""
306
+
307
+ if not operators:
308
+ operators = DEFAULT_OPERATORS.copy()
309
+ if not functions:
310
+ functions = DEFAULT_FUNCTIONS.copy()
311
+ if not names:
312
+ names = DEFAULT_NAMES.copy()
313
+
314
+ self.operators = operators
315
+ self.functions = functions
316
+ self.names = names
317
+
318
+ self.nodes = {
319
+ ast.Expr: self._eval_expr,
320
+ ast.Assign: self._eval_assign,
321
+ ast.AugAssign: self._eval_aug_assign,
322
+ ast.Import: self._eval_import,
323
+ ast.Num: self._eval_num,
324
+ ast.Str: self._eval_str,
325
+ ast.Name: self._eval_name,
326
+ ast.UnaryOp: self._eval_unaryop,
327
+ ast.BinOp: self._eval_binop,
328
+ ast.BoolOp: self._eval_boolop,
329
+ ast.Compare: self._eval_compare,
330
+ ast.IfExp: self._eval_ifexp,
331
+ ast.Call: self._eval_call,
332
+ ast.keyword: self._eval_keyword,
333
+ ast.Subscript: self._eval_subscript,
334
+ ast.Attribute: self._eval_attribute,
335
+ ast.Index: self._eval_index,
336
+ ast.Slice: self._eval_slice,
337
+ }
338
+
339
+ # py3k stuff:
340
+ if hasattr(ast, "NameConstant"):
341
+ self.nodes[ast.NameConstant] = self._eval_constant
342
+
343
+ # py3.6, f-strings
344
+ if hasattr(ast, "JoinedStr"):
345
+ self.nodes[ast.JoinedStr] = self._eval_joinedstr # f-string
346
+ self.nodes[
347
+ ast.FormattedValue
348
+ ] = self._eval_formattedvalue # formatted value in f-string
349
+
350
+ # py3.8 uses ast.Constant instead of ast.Num, ast.Str, ast.NameConstant
351
+ if hasattr(ast, "Constant"):
352
+ self.nodes[ast.Constant] = self._eval_constant
353
+
354
+ # Defaults:
355
+
356
+ self.ATTR_INDEX_FALLBACK = ATTR_INDEX_FALLBACK
357
+
358
+ # Check for forbidden functions:
359
+
360
+ for f in self.functions.values():
361
+ if f in DISALLOW_FUNCTIONS:
362
+ raise FeatureNotAvailable(
363
+ "This function {} is a really bad idea.".format(f)
364
+ )
365
+
366
+ def eval(self, expr):
367
+ """evaluate an expresssion, using the operators, functions and
368
+ names previously set up."""
369
+
370
+ # set a copy of the expression aside, so we can give nice errors...
371
+
372
+ self.expr = expr
373
+
374
+ # and evaluate:
375
+ return self._eval(ast.parse(expr.strip()).body[0])
376
+
377
+ def _eval(self, node):
378
+ """ The internal evaluator used on each node in the parsed tree. """
379
+
380
+ try:
381
+ handler = self.nodes[type(node)]
382
+ except KeyError:
383
+ raise FeatureNotAvailable(
384
+ "Sorry, {0} is not available in this "
385
+ "evaluator".format(type(node).__name__)
386
+ )
387
+
388
+ return handler(node)
389
+
390
+ def _eval_expr(self, node):
391
+ return self._eval(node.value)
392
+
393
+ def _eval_assign(self, node):
394
+ warnings.warn(
395
+ "Assignment ({}) attempted, but this is ignored".format(self.expr),
396
+ AssignmentAttempted,
397
+ )
398
+ return self._eval(node.value)
399
+
400
+ def _eval_aug_assign(self, node):
401
+ warnings.warn(
402
+ "Assignment ({}) attempted, but this is ignored".format(self.expr),
403
+ AssignmentAttempted,
404
+ )
405
+ return self._eval(node.value)
406
+
407
+ def _eval_import(self, node):
408
+ raise FeatureNotAvailable("Sorry, 'import' is not allowed.")
409
+ return self._eval(node.value)
410
+
411
+ @staticmethod
412
+ def _eval_num(node):
413
+ return node.n
414
+
415
+ @staticmethod
416
+ def _eval_str(node):
417
+ if len(node.s) > MAX_STRING_LENGTH:
418
+ raise IterableTooLong(
419
+ "String Literal in statement is too long!"
420
+ " ({0}, when {1} is max)".format(len(node.s), MAX_STRING_LENGTH)
421
+ )
422
+ return node.s
423
+
424
+ @staticmethod
425
+ def _eval_constant(node):
426
+ if hasattr(node.value, "__len__") and len(node.value) > MAX_STRING_LENGTH:
427
+ raise IterableTooLong(
428
+ "Literal in statement is too long!"
429
+ " ({0}, when {1} is max)".format(len(node.value), MAX_STRING_LENGTH)
430
+ )
431
+ return node.value
432
+
433
+ def _eval_unaryop(self, node):
434
+ return self.operators[type(node.op)](self._eval(node.operand))
435
+
436
+ def _eval_binop(self, node):
437
+ return self.operators[type(node.op)](
438
+ self._eval(node.left), self._eval(node.right)
439
+ )
440
+
441
+ def _eval_boolop(self, node):
442
+ if isinstance(node.op, ast.And):
443
+ vout = False
444
+ for value in node.values:
445
+ vout = self._eval(value)
446
+ if not vout:
447
+ return vout
448
+ return vout
449
+ elif isinstance(node.op, ast.Or):
450
+ for value in node.values:
451
+ vout = self._eval(value)
452
+ if vout:
453
+ return vout
454
+ return vout
455
+
456
+ def _eval_compare(self, node):
457
+ right = self._eval(node.left)
458
+ to_return = True
459
+ for operation, comp in zip(node.ops, node.comparators):
460
+ if not to_return:
461
+ break
462
+ left = right
463
+ right = self._eval(comp)
464
+ to_return = self.operators[type(operation)](left, right)
465
+ return to_return
466
+
467
+ def _eval_ifexp(self, node):
468
+ return (
469
+ self._eval(node.body) if self._eval(node.test) else self._eval(node.orelse)
470
+ )
471
+
472
+ def _eval_call(self, node):
473
+ if isinstance(node.func, ast.Attribute):
474
+ func = self._eval(node.func)
475
+ else:
476
+ try:
477
+ func = self.functions[node.func.id]
478
+ except KeyError:
479
+ raise FunctionNotDefined(node.func.id, self.expr)
480
+ except AttributeError as e:
481
+ raise FeatureNotAvailable("Lambda Functions not implemented")
482
+
483
+ if func in DISALLOW_FUNCTIONS:
484
+ raise FeatureNotAvailable("This function is forbidden")
485
+
486
+ return func(
487
+ *(self._eval(a) for a in node.args),
488
+ **dict(self._eval(k) for k in node.keywords)
489
+ )
490
+
491
+ def _eval_keyword(self, node):
492
+ return node.arg, self._eval(node.value)
493
+
494
+ def _eval_name(self, node):
495
+ try:
496
+ # This happens at least for slicing
497
+ # This is a safe thing to do because it is impossible
498
+ # that there is a true exression assigning to none
499
+ # (the compiler rejects it, so you can't even
500
+ # pass that to ast.parse)
501
+ if hasattr(self.names, "__getitem__"):
502
+ return self.names[node.id]
503
+ elif callable(self.names):
504
+ return self.names(node)
505
+ else:
506
+ raise InvalidExpression(
507
+ 'Trying to use name (variable) "{0}"'
508
+ ' when no "names" defined for'
509
+ " evaluator".format(node.id)
510
+ )
511
+
512
+ except KeyError:
513
+ if node.id in self.functions:
514
+ return self.functions[node.id]
515
+
516
+ raise NameNotDefined(node.id, self.expr)
517
+
518
+ def _eval_subscript(self, node):
519
+ container = self._eval(node.value)
520
+ key = self._eval(node.slice)
521
+ try:
522
+ return container[key]
523
+ except KeyError:
524
+ raise
525
+
526
+ def _eval_attribute(self, node):
527
+ for prefix in DISALLOW_PREFIXES:
528
+ if node.attr.startswith(prefix):
529
+ raise FeatureNotAvailable(
530
+ "Sorry, access to __attributes "
531
+ " or func_ attributes is not available. "
532
+ "({0})".format(node.attr)
533
+ )
534
+ if node.attr in DISALLOW_METHODS:
535
+ raise FeatureNotAvailable(
536
+ "Sorry, this method is not available. " "({0})".format(node.attr)
537
+ )
538
+ # eval node
539
+ node_evaluated = self._eval(node.value)
540
+
541
+ # Maybe the base object is an actual object, not just a dict
542
+ try:
543
+ return getattr(node_evaluated, node.attr)
544
+ except (AttributeError, TypeError):
545
+ pass
546
+
547
+ # TODO: is this a good idea? Try and look for [x] if .x doesn't work?
548
+ if self.ATTR_INDEX_FALLBACK:
549
+ try:
550
+ return node_evaluated[node.attr]
551
+ except (KeyError, TypeError):
552
+ pass
553
+
554
+ # If it is neither, raise an exception
555
+ raise AttributeDoesNotExist(node.attr, self.expr)
556
+
557
+ def _eval_index(self, node):
558
+ return self._eval(node.value)
559
+
560
+ def _eval_slice(self, node):
561
+ lower = upper = step = None
562
+ if node.lower is not None:
563
+ lower = self._eval(node.lower)
564
+ if node.upper is not None:
565
+ upper = self._eval(node.upper)
566
+ if node.step is not None:
567
+ step = self._eval(node.step)
568
+ return slice(lower, upper, step)
569
+
570
+ def _eval_joinedstr(self, node):
571
+ length = 0
572
+ evaluated_values = []
573
+ for n in node.values:
574
+ val = str(self._eval(n))
575
+ if len(val) + length > MAX_STRING_LENGTH:
576
+ raise IterableTooLong("Sorry, I will not evaluate something this long.")
577
+ evaluated_values.append(val)
578
+ return "".join(evaluated_values)
579
+
580
+ def _eval_formattedvalue(self, node):
581
+ if node.format_spec:
582
+ fmt = "{:" + self._eval(node.format_spec) + "}"
583
+ return fmt.format(self._eval(node.value))
584
+ return self._eval(node.value)
585
+
586
+
587
+ class EvalWithCompoundTypes(SimpleEval):
588
+ """
589
+ SimpleEval with additional Compound Types, and their respective
590
+ function editions. (list, tuple, dict, set).
591
+ """
592
+
593
+ def __init__(self, operators=None, functions=None, names=None):
594
+ super(EvalWithCompoundTypes, self).__init__(operators, functions, names)
595
+
596
+ self.functions.update(list=list, tuple=tuple, dict=dict, set=set)
597
+
598
+ self.nodes.update(
599
+ {
600
+ ast.Dict: self._eval_dict,
601
+ ast.Tuple: self._eval_tuple,
602
+ ast.List: self._eval_list,
603
+ ast.Set: self._eval_set,
604
+ ast.ListComp: self._eval_comprehension,
605
+ ast.GeneratorExp: self._eval_comprehension,
606
+ }
607
+ )
608
+
609
+ def eval(self, expr):
610
+ self._max_count = 0
611
+ return super(EvalWithCompoundTypes, self).eval(expr)
612
+
613
+ def _eval_dict(self, node):
614
+ return {self._eval(k): self._eval(v) for (k, v) in zip(node.keys, node.values)}
615
+
616
+ def _eval_tuple(self, node):
617
+ return tuple(self._eval(x) for x in node.elts)
618
+
619
+ def _eval_list(self, node):
620
+ return list(self._eval(x) for x in node.elts)
621
+
622
+ def _eval_set(self, node):
623
+ return set(self._eval(x) for x in node.elts)
624
+
625
+ def _eval_comprehension(self, node):
626
+ to_return = []
627
+
628
+ extra_names = {}
629
+
630
+ previous_name_evaller = self.nodes[ast.Name]
631
+
632
+ def eval_names_extra(node):
633
+ """
634
+ Here we hide our extra scope for within this comprehension
635
+ """
636
+ if node.id in extra_names:
637
+ return extra_names[node.id]
638
+ return previous_name_evaller(node)
639
+
640
+ self.nodes.update({ast.Name: eval_names_extra})
641
+
642
+ def recurse_targets(target, value):
643
+ """
644
+ Recursively (enter, (into, (nested, name), unpacking)) = \
645
+ and, (assign, (values, to), each
646
+ """
647
+ if isinstance(target, ast.Name):
648
+ extra_names[target.id] = value
649
+ else:
650
+ for t, v in zip(target.elts, value):
651
+ recurse_targets(t, v)
652
+
653
+ def do_generator(gi=0):
654
+ g = node.generators[gi]
655
+ for i in self._eval(g.iter):
656
+ self._max_count += 1
657
+
658
+ if self._max_count > MAX_COMPREHENSION_LENGTH:
659
+ raise IterableTooLong("Comprehension generates too many elements")
660
+ recurse_targets(g.target, i)
661
+ if all(self._eval(iff) for iff in g.ifs):
662
+ if len(node.generators) > gi + 1:
663
+ do_generator(gi + 1)
664
+ else:
665
+ to_return.append(self._eval(node.elt))
666
+
667
+ try:
668
+ do_generator()
669
+ finally:
670
+ self.nodes.update({ast.Name: previous_name_evaller})
671
+
672
+ return to_return
673
+
674
+
675
+ def simple_eval(expr, operators=None, functions=None, names=None):
676
+ """ Simply evaluate an expresssion """
677
+ s = SimpleEval(operators=operators, functions=functions, names=names)
678
+ return s.eval(expr)