Skip to content

Commit

Permalink
black applied
Browse files Browse the repository at this point in the history
  • Loading branch information
loechel committed Apr 1, 2018
1 parent d625a72 commit 6166f9b
Show file tree
Hide file tree
Showing 51 changed files with 707 additions and 705 deletions.
16 changes: 8 additions & 8 deletions src/RestrictedPython/Eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
maketrans = str.maketrans


nltosp = maketrans('\r\n', ' ')
nltosp = maketrans("\r\n", " ")

# No restrictions.
default_guarded_getattr = getattr
Expand All @@ -43,7 +43,7 @@ def default_guarded_getiter(ob):
class RestrictionCapableEval(object):
"""A base class for restricted code."""

globals = {'__builtins__': None}
globals = {"__builtins__": None}
# restricted
rcode = None

Expand All @@ -69,7 +69,7 @@ def __init__(self, expr):

def prepRestrictedCode(self):
if self.rcode is None:
result = compile_restricted_eval(self.expr, '<string>')
result = compile_restricted_eval(self.expr, "<string>")
if result.errors:
raise SyntaxError(result.errors[0])

Expand All @@ -79,10 +79,10 @@ def prepRestrictedCode(self):
def prepUnrestrictedCode(self):
if self.ucode is None:
exp_node = compile(
self.expr, '<string>', 'eval', ast.PyCF_ONLY_AST
self.expr, "<string>", "eval", ast.PyCF_ONLY_AST
)

co = compile(exp_node, '<string>', 'eval')
co = compile(exp_node, "<string>", "eval")

# Examine the ast to discover which names the expression needs.
if self.used is None:
Expand All @@ -102,9 +102,9 @@ def eval(self, mapping):
self.prepRestrictedCode()

global_scope = {
'_getattr_': default_guarded_getattr,
'_getitem_': default_guarded_getitem,
'_getiter_': default_guarded_getiter,
"_getattr_": default_guarded_getattr,
"_getitem_": default_guarded_getitem,
"_getiter_": default_guarded_getiter,
}

global_scope.update(self.globals)
Expand Down
184 changes: 92 additions & 92 deletions src/RestrictedPython/Guards.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,92 +28,92 @@
safe_builtins = {}

_safe_names = [
'None',
'False',
'True',
'abs',
'bool',
'callable',
'chr',
'complex',
'divmod',
'float',
'hash',
'hex',
'id',
'int',
'isinstance',
'issubclass',
'len',
'oct',
'ord',
'pow',
'range',
'repr',
'round',
'slice',
'str',
'tuple',
'zip',
"None",
"False",
"True",
"abs",
"bool",
"callable",
"chr",
"complex",
"divmod",
"float",
"hash",
"hex",
"id",
"int",
"isinstance",
"issubclass",
"len",
"oct",
"ord",
"pow",
"range",
"repr",
"round",
"slice",
"str",
"tuple",
"zip",
]

_safe_exceptions = [
'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BufferError',
'BytesWarning',
'DeprecationWarning',
'EOFError',
'EnvironmentError',
'Exception',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'NameError',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'ReferenceError',
'RuntimeError',
'RuntimeWarning',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'ZeroDivisionError',
"ArithmeticError",
"AssertionError",
"AttributeError",
"BaseException",
"BufferError",
"BytesWarning",
"DeprecationWarning",
"EOFError",
"EnvironmentError",
"Exception",
"FloatingPointError",
"FutureWarning",
"GeneratorExit",
"IOError",
"ImportError",
"ImportWarning",
"IndentationError",
"IndexError",
"KeyError",
"KeyboardInterrupt",
"LookupError",
"MemoryError",
"NameError",
"NotImplementedError",
"OSError",
"OverflowError",
"PendingDeprecationWarning",
"ReferenceError",
"RuntimeError",
"RuntimeWarning",
"StopIteration",
"SyntaxError",
"SyntaxWarning",
"SystemError",
"SystemExit",
"TabError",
"TypeError",
"UnboundLocalError",
"UnicodeDecodeError",
"UnicodeEncodeError",
"UnicodeError",
"UnicodeTranslateError",
"UnicodeWarning",
"UserWarning",
"ValueError",
"Warning",
"ZeroDivisionError",
]

if _compat.IS_PY2:
_safe_names.extend(
['basestring', 'cmp', 'long', 'unichr', 'unicode', 'xrange']
["basestring", "cmp", "long", "unichr", "unicode", "xrange"]
)
_safe_exceptions.extend(['StandardError'])
_safe_exceptions.extend(["StandardError"])
else:
_safe_names.extend(['__build_class__']) # needed to define new classes
_safe_names.extend(["__build_class__"]) # needed to define new classes

for name in _safe_names:
safe_builtins[name] = getattr(builtins, name)
Expand Down Expand Up @@ -199,24 +199,24 @@ def handler(self, *args):
class Wrapper(object):

def __init__(self, ob):
self.__dict__['ob'] = ob
self.__dict__["ob"] = ob

__setitem__ = _handler(
'__guarded_setitem__',
'object does not support item or slice assignment',
"__guarded_setitem__",
"object does not support item or slice assignment",
)

__delitem__ = _handler(
'__guarded_delitem__',
'object does not support item or slice assignment',
"__guarded_delitem__",
"object does not support item or slice assignment",
)

__setattr__ = _handler(
'__guarded_setattr__', 'attribute-less object (assign or del)'
"__guarded_setattr__", "attribute-less object (assign or del)"
)

__delattr__ = _handler(
'__guarded_delattr__', 'attribute-less object (assign or del)'
"__guarded_delattr__", "attribute-less object (assign or del)"
)

return Wrapper
Expand All @@ -231,7 +231,7 @@ def _full_write_guard():
def guard(ob):
# Don't bother wrapping simple types, or objects that claim to
# handle their own write security.
if type(ob) in safetypes or hasattr(ob, '_guarded_writes'):
if type(ob) in safetypes or hasattr(ob, "_guarded_writes"):
return ob

# Hand the object to the Wrapper instance, then return the instance.
Expand All @@ -247,14 +247,14 @@ def guarded_setattr(object, name, value):
setattr(full_write_guard(object), name, value)


safe_builtins['setattr'] = guarded_setattr
safe_builtins["setattr"] = guarded_setattr


def guarded_delattr(object, name):
delattr(full_write_guard(object), name)


safe_builtins['delattr'] = guarded_delattr
safe_builtins["delattr"] = guarded_delattr


def safer_getattr(object, name, getattr=getattr):
Expand All @@ -264,15 +264,15 @@ def safer_getattr(object, name, getattr=getattr):
http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/
"""
if isinstance(object, _compat.basestring) and name == 'format':
if isinstance(object, _compat.basestring) and name == "format":
raise NotImplementedError(
'Using format() on a %s is not safe.' % object.__class__.__name__
"Using format() on a %s is not safe." % object.__class__.__name__
)

return getattr(object, name)


safe_builtins['_getattr_'] = safer_getattr
safe_builtins["_getattr_"] = safer_getattr


def guarded_iter_unpack_sequence(it, spec, _getiter_):
Expand Down Expand Up @@ -303,11 +303,11 @@ def guarded_unpack_sequence(it, spec, _getiter_):
# If the sequence is shorter then expected the interpreter will raise
# 'ValueError: need more than X value to unpack' anyway
# => No childs are unpacked => nothing to protect.
if len(ret) < spec['min_len']:
if len(ret) < spec["min_len"]:
return ret

# For all child elements do the guarded unpacking again.
for (idx, child_spec) in spec['childs']:
for (idx, child_spec) in spec["childs"]:
ret[idx] = guarded_unpack_sequence(ret[idx], child_spec, _getiter_)

return ret
16 changes: 8 additions & 8 deletions src/RestrictedPython/Limits.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,38 +24,38 @@ def limited_range(iFirst, *args):
elif len(args) == 2:
iStart, iEnd, iStep = iFirst, args[0], args[1]
else:
raise AttributeError('range() requires 1-3 int arguments')
raise AttributeError("range() requires 1-3 int arguments")

if iStep == 0:
raise ValueError('zero step for range()')
raise ValueError("zero step for range()")

iLen = int((iEnd - iStart) / iStep)
if iLen < 0:
iLen = 0
if iLen >= RANGELIMIT:
raise ValueError('range() too large')
raise ValueError("range() too large")

return range(iStart, iEnd, iStep)


limited_builtins['range'] = limited_range
limited_builtins["range"] = limited_range


def limited_list(seq):
if isinstance(seq, str):
raise TypeError('cannot convert string to list')
raise TypeError("cannot convert string to list")

return list(seq)


limited_builtins['list'] = limited_list
limited_builtins["list"] = limited_list


def limited_tuple(seq):
if isinstance(seq, str):
raise TypeError('cannot convert string to tuple')
raise TypeError("cannot convert string to tuple")

return tuple(seq)


limited_builtins['tuple'] = limited_tuple
limited_builtins["tuple"] = limited_tuple
8 changes: 4 additions & 4 deletions src/RestrictedPython/PrintCollector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ def write(self, text):
self.txt.append(text)

def __call__(self):
return ''.join(self.txt)
return "".join(self.txt)

def _call_print(self, *objects, **kwargs):
if kwargs.get('file', None) is None:
kwargs['file'] = self
if kwargs.get("file", None) is None:
kwargs["file"] = self
else:
self._getattr_(kwargs['file'], 'write')
self._getattr_(kwargs["file"], "write")

print(*objects, **kwargs)
Loading

0 comments on commit 6166f9b

Please sign in to comment.