Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def require(self, value):
if value is None:
return load("None")
if isinstance(value, NATIVE_NUMBERS):
return ast.Num(value)
node = self.imports.get(value)
if node is None:
# we come up with a unique symbol based on the class name
name = "_%s" % getattr(value, '__name__', str(value)).\
rsplit('.', 1)[-1]
node = load(name)
self.imports[value] = store(node.id)
return node
self.lines = []
while self.imports:
value, node = self.imports.popitem()
if isinstance(value, types.ModuleType):
stmt = ast.Import(
names=[ast.alias(name=value.__name__, asname=node.id)])
elif hasattr(value, '__name__'):
path = reverse_builtin_map.get(value)
if path is None:
path = value.__module__
name = value.__name__
stmt = ast.ImportFrom(
module=path,
names=[ast.alias(name=name, asname=node.id)],
level=0,
)
else:
raise TypeError(value)
self.visit(stmt)
# Clear last import
self.flush()
# Stich together lines
self.lines += defines + body
def wrapper(*vargs, **kwargs):
symbols = dict(zip(args, vargs + defaults))
symbols.update(kwargs)
class Visitor(ast.NodeVisitor):
def visit_FunctionDef(self, node):
self.generic_visit(node)
name = symbols.get(node.name, self)
if name is not self:
node_annotations[node] = ast.FunctionDef(
name=name,
args=node.args,
body=node.body,
decorator_list=getattr(node, "decorator_list", []),
)
def visit_Name(self, node):
value = symbols.get(node.id, self)
if value is not self:
if isinstance(value, basestring):
self._write('yield')
if getattr(node, 'value', None):
self._write(' ')
self.visit(node.value)
comparison_operators = {
ast.Eq: '==',
ast.NotEq: '!=',
ast.Lt: '<',
ast.LtE: '<=',
ast.Gt: '>',
ast.GtE: '>=',
ast.Is: 'is',
ast.IsNot: 'is not',
ast.In: 'in',
ast.NotIn: 'not in',
}
# Compare(expr left, cmpop* ops, expr* comparators)
@with_parens
def visit_Compare(self, node):
self.visit(node.left)
for op, comparator in zip(node.ops, node.comparators):
self._write(' ' + self.comparison_operators[op.__class__] + ' ')
self.visit(comparator)
# Call(expr func, expr* args, keyword* keywords,
# expr? starargs, expr? kwargs)
def visit_Call(self, node):
self.visit(node.func)
self._write('(')
first = True
name, node = self.defines.popitem()
assignment = ast.Assign(targets=[store(name)], value=node)
self.visit(assignment)
# Make sure we terminate the line printer
self.flush()
# Clear lines array for import visits
defines = self.lines
self.lines = []
while self.imports:
value, node = self.imports.popitem()
if isinstance(value, types.ModuleType):
stmt = ast.Import(
names=[ast.alias(name=value.__name__, asname=node.id)])
elif hasattr(value, '__name__'):
path = reverse_builtin_map.get(value)
if path is None:
path = value.__module__
name = value.__name__
stmt = ast.ImportFrom(
module=path,
names=[ast.alias(name=name, asname=node.id)],
level=0,
)
else:
raise TypeError(value)
self.visit(stmt)
# Clear lines array for import visits
defines = self.lines
self.lines = []
while self.imports:
value, node = self.imports.popitem()
if isinstance(value, types.ModuleType):
stmt = ast.Import(
names=[ast.alias(name=value.__name__, asname=node.id)])
elif hasattr(value, '__name__'):
path = reverse_builtin_map.get(value)
if path is None:
path = value.__module__
name = value.__name__
stmt = ast.ImportFrom(
module=path,
names=[ast.alias(name=name, asname=node.id)],
level=0,
)
else:
raise TypeError(value)
self.visit(stmt)
# Clear last import
self.flush()
# Stich together lines
self.lines += defines + body
lambda attribute:
isinstance(attribute, nodes.Attribute) and
isinstance(attribute.expression, ast.Str)
)
"""Support classes for generating code from abstract syntax trees."""
try:
import ast
except ImportError:
from chameleon import ast25 as ast
import sys
import logging
import weakref
import collections
node_annotations = weakref.WeakKeyDictionary()
try:
node_annotations[ast.Name()] = None
except TypeError:
logging.debug(
"Unable to create weak references to AST nodes. " \
"A lock will be used around compilation loop."
)
node_annotations = {}
__docformat__ = 'restructuredtext en'
def annotated(value):
node = load("annotation")
node_annotations[node] = value
return node
from ..exc import ParseError
from ..exc import CompilationError
from ..utils import decode_htmlentities
try:
str = unicode
except NameError:
long = int
missing = object()
re_trim = re.compile(r'($\s+|\s+^)', re.MULTILINE)
EMPTY_DICT = Static(ast.Dict(keys=[], values=[]))
def skip(node):
return node
def wrap(node, *wrappers):
for wrapper in reversed(wrappers):
node = wrapper(node)
return node
def validate_attributes(attributes, namespace, whitelist):
for ns, name in attributes:
if ns == namespace and name not in whitelist:
raise CompilationError(
def __getattr__(self, name):
if name.startswith('__'):
raise AttributeError(name)
return _ast.__dict__.get(name) or getattr(_ast, self.aliases[name])