def noneSpecialFunction(cv):
"""If the old type is 'None' (which won't show up in the original), move up in the AST to get the metadata"""
if (not isinstance(cv, AddVector)) and cv.oldSubtree == None:
cvCopy = cv.deepcopy()
if cv.path[0] == ('value', 'Return'):
cv.oldSubtree = deepcopy(cvCopy.traverseTree(cv.start))
cv.newSubtree = ast.Return(cv.newSubtree)
cv.path = cv.path[1:]
elif cv.path[0] == ('value', 'Name Constant'):
cv.oldSubtree = deepcopy(cvCopy.traverseTree(cv.start))
cv.newSubtree = ast.NameConstant(cv.newSubtree)
cv.path = cv.path[1:]
elif cv.path[0] in [('lower', 'Slice'), ('upper', 'Slice'), ('step', 'Slice')]:
tmpNew = cv.newSubtree
cvCopy = cv.deepcopy()
cv.oldSubtree = deepcopy(cvCopy.traverseTree(cv.start))
cv.newSubtree = deepcopy(cv.oldSubtree) # use the same slice
if cv.path[0][0] == 'lower':
cv.newSubtree.lower = tmpNew
elif cv.path[0][0] == 'upper':
cv.newSubtree.upper = tmpNew
else:
cv.newSubtree.step = tmpNew
cv.path = cv.path[1:] # get rid of None and the val
else:
log("Individualize\tmapEdit\tMissing option in None special case 1: " + str(cv.path[0]), "bug")
elif cv.oldSubtree == "None":
cv.path = cv.path[1:] # get rid of None and the id
cvCopy = cv.deepcopy()
cv.oldSubtree = deepcopy(cvCopy.traverseTree(cv.start))
if cv.path[0] == ('value', 'Return'):
cv.newSubtree = ast.Return(ast.Name(cv.newSubtree, ast.Load()))
else:
log("Individualize\tmapEdit\tMissing option in None special case 2: " + str(cv.path[0]), "bug")
cv.path = cv.path[1:]
return cv
python类Return()的实例源码
def getFirst(a):
# Return the first value if the list has at least one element
return a[0] if len(a) > 0 else None
def isStatement(a):
"""Determine whether the given node is a statement (vs an expression)"""
return type(a) in [ ast.Module, ast.Interactive, ast.Expression, ast.Suite,
ast.FunctionDef, ast.ClassDef, ast.Return, ast.Delete,
ast.Assign, ast.AugAssign, ast.For, ast.While,
ast.If, ast.With, ast.Raise, ast.Try,
ast.Assert, ast.Import, ast.ImportFrom, ast.Global,
ast.Expr, ast.Pass, ast.Break, ast.Continue ]
def _transform_multiline_return_statement(return_statement):
return ast.Return(value=return_statement, lineno=return_statement.lineno, col_offset = return_statement.col_offset)
def _compile(self):
c = _NameSubstitute()
t = c.visit(copy(self._tree))
name = repr(self)
maxarg = max((int(name[1:]) for name in c.name_cache), default=0) + 1
args = [
ast.arg(arg='_%d' % n, annotation=None)
for n in range(1, maxarg)
]
code = compile(
ast.fix_missing_locations(ast.Module(
body=[
ast.FunctionDef(
name=name,
args=ast.arguments(
args=args,
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[],
),
body=[ast.Return(value=t)],
decorator_list=[],
returns=None,
lineno=1,
col_offset=0,
),
],
)),
name,
'exec',
)
ns = {}
exec(code, ns)
return asconstants(**self._constants)(ns[name])
def get_configuration_type():
"""
Return the type of the current configuration.
Returns
-------
s : str or None
Depending on the type of the currenct configuration, `s` equals
either the constant SQL_MYSQL or SQL_SQLITE from defines.py. If
no configuration is available, return None.
"""
if cfg.current_server in cfg.server_configuration:
return cfg.server_configuration[cfg.current_server]["type"]
else:
return None
def _make_fn(name, chain_fn, args, defaults):
args_with_self = ['_self'] + list(args)
arguments = [_ast.Name(id=arg, ctx=_ast.Load()) for arg in args_with_self]
defs = [_ast.Name(id='_def{0}'.format(idx), ctx=_ast.Load()) for idx, _ in enumerate(defaults)]
if _PY2:
parameters = _ast.arguments(args=[_ast.Name(id=arg, ctx=_ast.Param()) for arg in args_with_self],
defaults=defs)
else:
parameters = _ast.arguments(args=[_ast.arg(arg=arg) for arg in args_with_self],
kwonlyargs=[],
defaults=defs,
kw_defaults=[])
module_node = _ast.Module(body=[_ast.FunctionDef(name=name,
args=parameters,
body=[_ast.Return(value=_ast.Call(func=_ast.Name(id='_chain', ctx=_ast.Load()),
args=arguments,
keywords=[]))],
decorator_list=[])])
module_node = _ast.fix_missing_locations(module_node)
# compile the ast
code = compile(module_node, '<string>', 'exec')
# and eval it in the right context
globals_ = {'_chain': chain_fn}
locals_ = dict(('_def{0}'.format(idx), value) for idx, value in enumerate(defaults))
eval(code, globals_, locals_)
# extract our function from the newly created module
return locals_[name]
########################################################################
# Produce a docstring for the class.
def _nt_getnewargs(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
def generic_visit(self, node):
if (isinstance(node, ast.stmt) and self.references_arg(node)) or isinstance(node, ast.Return):
return self.get_waits() + [node]
return NodeTransformer.generic_visit(self, node)
def analysis_function(self, function_node, args_type=[]):
variables = Variables()
return_type = Type.VOID
for node in function_node.body:
if isinstance(node, ast.Assign):
self.analysis_assign_node(variables, node)
elif isinstance(node, ast.Return):
return_type = self.get_type(node.value)
if return_type is None:
return_type = Type.VOID
generator = CodeGenerator(self.code,variables=variables)
return generator, return_type
def test_builtin_frozenset(self):
self.check_builtin_func('frozenset',
"return frozenset(('abc',))",
ast.Return(ast.Constant(value=frozenset(('abc',)))))
self.check_builtin_func('frozenset',
"return frozenset()",
ast.Return(ast.Constant(value=frozenset())))
self.check_dont_optimize_func('frozenset(([],))')
def get_runner(path, **kw):
"""
Partial application of path to run_code(). Return function 'run' so run(source) => result.
"""
def run(source):
return run_code(path, source, **kw)
return run
def is_rewrite_float32(self):
"""
Return whether an ArrayStorage transform is used such that float arrays are rewritten to float32 format.
"""
return any(getattr(t, 'use_float32', False) for t in self.transformL)
def is_use_4channel(self):
"""
Return whether an ArrayStorage transform is used such that float arrays are rewritten to have 4 channels.
"""
return any(getattr(t, 'use_4channel', False) for t in self.transformL)
def is_known_type(s):
'''
Return True if s is nothing but a single known type.
Recursively test inner types in square brackets.
'''
return ReduceTypes().is_known_type(s)
def reduce_types(aList, name=None, trace=False):
'''
Return a string containing the reduction of all types in aList.
The --trace-reduce command-line option sets trace=True.
If present, name is the function name or class_name.method_name.
'''
return ReduceTypes(aList, name, trace).reduce_types()
# Top-level functions
def truncate(s, n):
'''Return s truncated to n characters.'''
return s if len(s) <= n else s[:n-3] + '...'
def visit(self, node):
'''Return the formatted version of an Ast node, or list of Ast nodes.'''
if isinstance(node, (list, tuple)):
return ','.join([self.visit(z) for z in node])
elif node is None:
return 'None'
else:
assert isinstance(node, ast.AST), node.__class__.__name__
method_name = 'do_' + node.__class__.__name__
method = getattr(self, method_name)
s = method(node)
# assert type(s) == type('abc'), (node, type(s))
assert g.isString(s), type(s)
return s
# Contexts...
# 2: ClassDef(identifier name, expr* bases,
# stmt* body, expr* decorator_list)
# 3: ClassDef(identifier name, expr* bases,
# keyword* keywords, expr? starargs, expr? kwargs
# stmt* body, expr* decorator_list)
#
# keyword arguments supplied to call (NULL identifier for **kwargs)
# keyword = (identifier? arg, expr value)
def get_import_names(self, node):
'''Return a list of the the full file names in the import statement.'''
result = []
for ast2 in node.names:
if self.kind(ast2) == 'alias':
data = ast2.name, ast2.asname
result.append(data)
else:
print('unsupported kind in Import.names list', self.kind(ast2))
return result
def isString(self, s):
'''Return True if s is any string, but not bytes.'''
# pylint: disable=no-member
if isPython3:
return isinstance(s, str)
else:
return isinstance(s, types.StringTypes)