Skip to content

Commit

Permalink
apply flake8 fixes for better readability.
Browse files Browse the repository at this point in the history
  • Loading branch information
loechel committed Sep 18, 2017
1 parent 3d3b267 commit 676daad
Show file tree
Hide file tree
Showing 4 changed files with 194 additions and 108 deletions.
5 changes: 3 additions & 2 deletions src/RestrictedPython/Eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ def prepUnrestrictedCode(self):
self.expr,
'<string>',
'eval',
ast.PyCF_ONLY_AST)
ast.PyCF_ONLY_AST,
)

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

Expand All @@ -99,7 +100,7 @@ def eval(self, mapping):

global_scope = {
'_getattr_': default_guarded_getattr,
'_getitem_': default_guarded_getitem
'_getitem_': default_guarded_getitem,
}

global_scope.update(self.globals)
Expand Down
17 changes: 11 additions & 6 deletions src/RestrictedPython/Guards.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
'slice',
'str',
'tuple',
'zip'
'zip',
]

_safe_exceptions = [
Expand Down Expand Up @@ -207,19 +207,23 @@ def __init__(self, ob):

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

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

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

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


Expand Down Expand Up @@ -265,7 +269,8 @@ def safer_getattr(object, name, getattr=getattr):
"""
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)


Expand Down
147 changes: 88 additions & 59 deletions src/RestrictedPython/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,45 @@


CompileResult = namedtuple(
'CompileResult', 'code, errors, warnings, used_names')
'CompileResult',
'code, errors, warnings, used_names',
)
syntax_error_template = (
'Line {lineno}: {type}: {msg} in on statement: {statement}')
'Line {lineno}: {type}: {msg} in on statement: {statement}'
)


def _compile_restricted_mode(
source,
filename='<string>',
mode="exec",
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
source,
filename='<string>',
mode="exec",
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer,
):
byte_code = None
errors = []
warnings = []
used_names = {}
if policy is None:
# Unrestricted Source Checks
byte_code = compile(source, filename, mode=mode, flags=flags,
dont_inherit=dont_inherit)
byte_code = compile(
source,
filename,
mode=mode,
flags=flags,
dont_inherit=dont_inherit,
)
elif issubclass(policy, RestrictingNodeTransformer):
c_ast = None
allowed_source_types = [str, ast.Module]
if IS_PY2:
allowed_source_types.append(unicode) # NOQA: F821,E501 # PY2 only statement, in Python 2 only module
if not issubclass(type(source), tuple(allowed_source_types)):
raise TypeError('Not allowed source type: '
'"{0.__class__.__name__}".'.format(source))
raise TypeError(
'Not allowed source type: '
'"{0.__class__.__name__}".'.format(source),
)
c_ast = None
# workaround for pypy issue https://bitbucket.org/pypy/pypy/issues/2552
if isinstance(source, ast.Module):
Expand All @@ -45,81 +56,93 @@ def _compile_restricted_mode(
except (TypeError, ValueError) as e:
errors.append(str(e))
except SyntaxError as v:
errors.append(syntax_error_template.format(
lineno=v.lineno,
type=v.__class__.__name__,
msg=v.msg,
statement=v.text.strip()
))
errors.append(
syntax_error_template.format(
lineno=v.lineno,
type=v.__class__.__name__,
msg=v.msg,
statement=v.text.strip(),
),
)
if c_ast:
policy(errors, warnings, used_names).visit(c_ast)
if not errors:
byte_code = compile(c_ast, filename, mode=mode # ,
# flags=flags,
# dont_inherit=dont_inherit
)
byte_code = compile(
c_ast,
filename,
mode=mode,
# flags=flags,
# dont_inherit=dont_inherit
)
else:
raise TypeError('Unallowed policy provided for RestrictedPython')
return CompileResult(byte_code, tuple(errors), warnings, used_names)


def compile_restricted_exec(
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer,
):
"""Compile restricted for the mode `exec`."""
return _compile_restricted_mode(
source,
filename=filename,
mode='exec',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
policy=policy,
)


def compile_restricted_eval(
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer,
):
"""Compile restricted for the mode `eval`."""
return _compile_restricted_mode(
source,
filename=filename,
mode='eval',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
policy=policy,
)


def compile_restricted_single(
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer,
):
"""Compile restricted for the mode `single`."""
return _compile_restricted_mode(
source,
filename=filename,
mode='single',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
policy=policy,
)


def compile_restricted_function(
p, # parameters
body,
name,
filename='<string>',
globalize=None, # List of globals (e.g. ['here', 'context', ...])
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
p, # parameters
body,
name,
filename='<string>',
globalize=None, # List of globals (e.g. ['here', 'context', ...])
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer,
):
"""Compile a restricted code object for a function.
The globalize argument, if specified, is a list of variable names to be
Expand Down Expand Up @@ -165,8 +188,11 @@ def compile_restricted_function(
# We don't want the user to need to understand this.
if globalize:
body_ast.body.insert(0, ast.Global(globalize))
wrapper_ast = ast.parse('def masked_function_name(%s): pass' % p,
'<func wrapper>', 'exec')
wrapper_ast = ast.parse(
'def masked_function_name(%s): pass' % p,
'<func wrapper>',
'exec',
)
# In case the name you chose for your generated function is not a
# valid python identifier we set it after the fact
function_ast = wrapper_ast.body[0]
Expand All @@ -182,18 +208,20 @@ def compile_restricted_function(
mode='exec',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
policy=policy,
)

return result


def compile_restricted(
source,
filename='<unknown>',
mode='exec',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
source,
filename='<unknown>',
mode='exec',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer,
):
"""Replacement for the built-in compile() function.
policy ... `ast.NodeTransformer` class defining the restrictions.
Expand All @@ -206,13 +234,14 @@ def compile_restricted(
mode=mode,
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
policy=policy,
)
else:
raise TypeError('unknown mode %s', mode)
for warning in result.warnings:
warnings.warn(
warning,
SyntaxWarning
SyntaxWarning,
)
if result.errors:
raise SyntaxError(result.errors)
Expand Down
Loading

0 comments on commit 676daad

Please sign in to comment.