本文整理汇总了Python中ast.alias函数的典型用法代码示例。如果您正苦于以下问题:Python alias函数的具体用法?Python alias怎么用?Python alias使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了alias函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_import_from
def test_import_from():
assert eq(
import_from.bar[alias.foo, alias["foo", "baz"]],
ast.ImportFrom(
module="bar", names=[ast.alias(name="foo", asname=None), ast.alias(name="foo", asname="baz")], level=0
),
)
开发者ID:cpcloud,项目名称:cysqlite3,代码行数:7,代码来源:test_miniast.py
示例2: visit_Module
def visit_Module(self, node):
pre_nodes = list(itertools.takewhile(
lambda node: (self._is_docstring(node)
or self._is_future_import(node)),
node.body))
rest_nodes = [self.visit(n) for n in node.body[len(pre_nodes):]]
importnode = ast.ImportFrom(
module='hesitate.driver',
names=[
ast.alias(
name='should_assert',
asname=self.ASSERTION_TEST_IMPORTED_NAME),
ast.alias(
name='timed',
asname=self.ASSERTION_TIMER_IMPORTED_NAME)],
lineno=1,
col_offset=0,
level=0)
if pre_nodes:
importnode = ast.copy_location(importnode, pre_nodes[0])
new_mod = ast.Module(
body=pre_nodes + [importnode] + rest_nodes,
lineno=1,
col_offset=0)
return new_mod
开发者ID:pombredanne,项目名称:hesitate-py,代码行数:29,代码来源:rewriter.py
示例3: test_simple_statements
def test_simple_statements(self):
# Simple statements can be put on a single line as long as the scope
# has not changed.
for body, expect in [(ast.Expr(ast.Num(42)), '42'),
(ast.Import([ast.alias('a', None)]), 'import a'),
(ast.ImportFrom('b', [ast.alias('a', None)], 1),
'from .b import a'),
(ast.Break(), 'break'),
(ast.Continue(), 'continue'),
(ast.Pass(), 'pass'),
(ast.Assign([ast.Name('X', ast.Store())], ast.Num(42)),
'X=42'),
(ast.Delete([ast.Name('X', ast.Del())]), 'del X'),
(ast.Raise(None, None), 'raise'),
(ast.Return(None), 'return'),
(ast.AugAssign(ast.Name('X', ast.Store()), ast.Add(),
ast.Num(42)), 'X+=42'),
(ast.Assert(ast.Num(42), None), 'assert 42'),
(ast.Global(['x']), 'global x'),
(ast.Nonlocal(['x']), 'nonlocal x'),
]:
if_simple = ast.If(ast.Num(42), [body], None)
self.verify(if_simple, 'if 42:{}'.format(expect))
if_multiple_simples = ast.If(ast.Num(42), [ast.Pass(), ast.Pass()],
None)
self.verify(if_multiple_simples, 'if 42:pass;pass')
inner_if = ast.If(ast.Num(6), [ast.Pass()], None)
funky_if = ast.If(ast.Num(42), [ast.Break(), ast.Continue(), inner_if,
ast.Break(), ast.Continue()],
None)
self.verify(funky_if,
'if 42:\n break;continue\n if 6:pass\n break;continue')
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:33,代码来源:test_mnfy.py
示例4: __init__
def __init__(self):
scope = {}
import_asts = []
# add in required functions into scope for call availability
for func_name in dir(function):
fn = getattr(function, func_name)
if callable(fn):
scope[func_name] = fn
import_ast = ast.ImportFrom(
'vectordatasource.meta.function',
[ast.alias(func_name, None)],
0,
)
import_asts.append(import_ast)
scope['util'] = util
utils_import_ast = ast.ImportFrom(
'vectordatasource',
[ast.alias('util', None)],
0,
)
import_asts.append(utils_import_ast)
self.import_asts = import_asts
self.scope = scope
开发者ID:tilezen,项目名称:vector-datasource,代码行数:26,代码来源:python.py
示例5: test_Import
def test_Import(self):
self.verify(ast.Import([ast.alias('spam', None)]), 'import spam')
self.verify(ast.Import([ast.alias('spam', 'bacon')]),
'import spam as bacon')
self.verify(ast.Import([ast.alias('spam', None),
ast.alias('bacon', 'bacn'),
ast.alias('eggs', None)]),
'import spam,bacon as bacn,eggs')
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:8,代码来源:test_mnfy.py
示例6: _process_instr_import_name
def _process_instr_import_name(instr, queue, stack, body, context):
"""
Process an IMPORT_NAME instruction.
Side Effects
------------
Pops two instuctions from `stack`
Consumes instructions from `queue` to the end of the import statement.
Appends an ast.Import or ast.ImportFrom node to `body`.
"""
# If this is "import module", fromlist is None.
# If this this is "from module import a, b fromlist will be ('a', 'b').
fromlist = stack.pop().arg
# level argument to __import__. Should be 0, 1, or 2.
level = stack.pop().arg
module = instr.arg
if fromlist is None: # Regular import.
attr_loads = _pop_import_LOAD_ATTRs(module, queue)
store = queue.popleft()
# There are two cases where we should emit an alias:
# import a as <anything but a>
# import a.b.c as <anything (including a)>
if attr_loads or module.split('.')[0] != store.arg:
asname = store.arg
else:
asname = None
body.append(
ast.Import(
names=[
ast.alias(
name=module,
asname=(asname),
),
],
level=level,
),
)
return
elif fromlist == ('*',): # From module import *.
expect(queue.popleft(), instrs.IMPORT_STAR, "after IMPORT_NAME")
body.append(
ast.ImportFrom(
module=module,
names=[ast.alias(name='*', asname=None)],
level=level,
),
)
return
# Consume a pair of IMPORT_FROM, STORE_NAME instructions for each entry in
# fromlist.
names = list(map(make_importfrom_alias(queue, body, context), fromlist))
body.append(ast.ImportFrom(module=module, names=names, level=level))
# Remove the final POP_TOP of the imported module.
expect(queue.popleft(), instrs.POP_TOP, "after 'from import'")
开发者ID:jcrist,项目名称:codetransformer,代码行数:58,代码来源:decompiler.py
示例7: compile_import_expression
def compile_import_expression(self, expr):
def _compile_import(expr, module, names=None, importer=ast.Import):
return [
importer(
lineno=expr.start_line,
col_offset=expr.start_column,
module=ast_str(module),
names=names or [ast.alias(name=ast_str(module), asname=None)],
level=0,
)
]
expr.pop(0) # index
rimports = []
while len(expr) > 0:
iexpr = expr.pop(0)
if isinstance(iexpr, HySymbol):
rimports += _compile_import(expr, iexpr)
continue
if isinstance(iexpr, HyList) and len(iexpr) == 1:
rimports += _compile_import(expr, iexpr.pop(0))
continue
if isinstance(iexpr, HyList) and iexpr:
module = iexpr.pop(0)
entry = iexpr[0]
if isinstance(entry, HyKeyword) and entry == HyKeyword(":as"):
assert len(iexpr) == 2, "garbage after aliased import"
iexpr.pop(0) # :as
alias = iexpr.pop(0)
rimports += _compile_import(
expr, ast_str(module), [ast.alias(name=ast_str(module), asname=ast_str(alias))]
)
continue
if isinstance(entry, HyList):
names = []
while entry:
sym = entry.pop(0)
if entry and isinstance(entry[0], HyKeyword):
entry.pop(0)
alias = ast_str(entry.pop(0))
else:
alias = None
names += [ast.alias(name=ast_str(sym), asname=alias)]
rimports += _compile_import(expr, module, names, ast.ImportFrom)
continue
raise TypeError("Unknown entry (`%s`) in the HyList" % (entry))
if len(rimports) == 1:
return rimports[0]
else:
return rimports
开发者ID:eigenhombre,项目名称:hy,代码行数:57,代码来源:compiler.py
示例8: p_module_encoding
def p_module_encoding(p): # noqa
"""module_encoding : ENCODING module"""
global debug_on
p[0] = ast.Module(
[ast.ImportFrom('concat.libconcat', [ast.alias('*', None)], 0),
ast.Import([ast.alias('concat.stdlib.builtins', None)])] +
(ast.parse('stack.debug = True').body if debug_on else []) +
p[2].body)
_set_line_info(p)
开发者ID:jmanuel1,项目名称:concat,代码行数:9,代码来源:parse.py
示例9: run
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.body:
# Nothing to do.
return
# Insert some special imports at the top of the module but after any
# docstrings and __future__ imports.
aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
ast.alias("_pytest.assertion.rewrite", "@pytest_ar")]
doc = getattr(mod, "docstring", None)
expect_docstring = doc is None
if doc is not None and self.is_rewrite_disabled(doc):
return
pos = 0
lineno = 1
for item in mod.body:
if (expect_docstring and isinstance(item, ast.Expr) and
isinstance(item.value, ast.Str)):
doc = item.value.s
if self.is_rewrite_disabled(doc):
return
expect_docstring = False
elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
item.module != "__future__"):
lineno = item.lineno
break
pos += 1
else:
lineno = item.lineno
imports = [ast.Import([alias], lineno=lineno, col_offset=0)
for alias in aliases]
mod.body[pos:pos] = imports
# Collect asserts.
nodes = [mod]
while nodes:
node = nodes.pop()
for name, field in ast.iter_fields(node):
if isinstance(field, list):
new = []
for i, child in enumerate(field):
if isinstance(child, ast.Assert):
# Transform assert.
new.extend(self.visit(child))
else:
new.append(child)
if isinstance(child, ast.AST):
nodes.append(child)
setattr(node, name, new)
elif (isinstance(field, ast.AST) and
# Don't recurse into expressions as they can't contain
# asserts.
not isinstance(field, ast.expr)):
nodes.append(field)
开发者ID:ceridwen,项目名称:pytest,代码行数:53,代码来源:rewrite.py
示例10: test_combining_ImportFrom
def test_combining_ImportFrom(self):
# Combine ImportFrom when the 'from' clause matches.
imp1 = ast.ImportFrom('X', [ast.alias('Y', None)], 1)
imp2 = ast.ImportFrom('X', [ast.alias('Z', None)], 1)
module = ast.Module([imp1, imp2])
new_ast = self.transform.visit(module)
self.assertEqual(len(module.body), 1)
imp = new_ast.body[0]
self.assertEqual(len(imp.names), 2)
for alias, (name, asname) in zip(imp.names,
(('Y', None), ('Z', None))):
self.assertEqual(alias.name, name)
self.assertEqual(alias.asname, asname)
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:13,代码来源:test_mnfy.py
示例11: generate
def generate(self, element:Element, GC:GenerationContext):
acode = element.code
imports_list = []
import_statements = []
with GC.let(domain=ExDom):
for import_element in acode[1:]:
if _is_module_path(import_element):
to_import_name = _get_module_path(import_element)
imports_list.append(ast.alias(name=to_import_name, asname=None))
elif is_form(import_element.code, "as"):
to_import_name = _get_module_path(import_element.code[1])
to_import_asname = _get_name(import_element.code[2])
imports_list.append(ast.alias(name=to_import_name,
asname=to_import_asname))
elif is_form(import_element.code) or is_seq(import_element.code):
to_import_module_name = _get_module_path(import_element.code[0])
imported_names_from_module = []
for to_import_item_element in import_element.code[1:]:
if is_identifier(to_import_item_element):
to_import_name = _get_name(to_import_item_element)
imported_names_from_module.append(ast.alias(name=to_import_name, asname=None))
elif is_form(to_import_item_element.code, "as"):
to_import_name = _get_name(to_import_item_element.code[1])
to_import_asname = _get_name(to_import_item_element.code[2])
imported_names_from_module.append(ast.alias(name=to_import_name,
asname=to_import_asname))
import_statements.append(ast.ImportFrom(to_import_module_name, imported_names_from_module, 0))
else:
raise CodeGenerationError(import_element.range, "Special form `import` expected an import specifier but found `%s`."
"For example:"
"```"
"import"
" a.b.c"
" x.y.z as name"
" u.v.w( var1, var2 as v )"
"```" % succinct_lisp_printer(import_element))
if len(imports_list) > 0:
import_statements.append(ast.Import(imports_list))
return import_statements
开发者ID:bloff,项目名称:rmtc-parsing,代码行数:50,代码来源:import.py
示例12: test_ImportFrom
def test_ImportFrom(self):
# from X import Y
from_X = ast.ImportFrom('X', [ast.alias('Y', None)], 0)
self.verify(from_X, 'from X import Y')
# from . import Y
from_dot = ast.ImportFrom(None, [ast.alias('Y', None)], 1)
self.verify(from_dot, 'from . import Y')
# from .X import Y
from_dot_X = ast.ImportFrom('X', [ast.alias('Y', None)], 1)
self.verify(from_dot_X, 'from .X import Y')
# from X import Y, Z
from_X_multi = ast.ImportFrom('X', [ast.alias('Y', None),
ast.alias('Z', None)], 0)
self.verify(from_X_multi, 'from X import Y,Z')
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:14,代码来源:test_mnfy.py
示例13: visit_Module
def visit_Module(self, node):
""" Add the imports needed to run symbolically """
node = self.generic_visit(node)
if self.se_dict:
import_se_dict = ast.ImportFrom(module="se_dict", names=[ast.alias(name="SeDict", asname=None)], level=0)
import_instrumentation = ast.ImportFrom(module="symbolic.instrumentation", names=[ast.alias(name="whichBranch", asname=None)], level=0)
import_extract = ast.ImportFrom(module="symbolic.symbolic_types", names=[ast.alias(name="getConcrete", asname=None)], level=0)
ord_function = ast.parse(ord_str).body
#if self.se_dict:
# node.body = [import_se_dict,import_instrumentation,import_extract] + ord_function + node.body
#else:
node.body = [import_instrumentation,import_extract] + ord_function + node.body
return node
开发者ID:algobardo,项目名称:PyExZ3,代码行数:14,代码来源:predigest.py
示例14: run
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.body:
# Nothing to do.
return
# Insert some special imports at the top of the module but after any
# docstrings and __future__ imports.
aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
ast.alias("_pytest.assertion.rewrite", "@pytest_ar")]
expect_docstring = True
pos = 0
lineno = 0
for item in mod.body:
if (expect_docstring and isinstance(item, ast.Expr) and
isinstance(item.value, ast.Str)):
doc = item.value.s
if "PYTEST_DONT_REWRITE" in doc:
# The module has disabled assertion rewriting.
return
lineno += len(doc) - 1
expect_docstring = False
elif (not isinstance(item, ast.ImportFrom) or item.level > 0 and
item.identifier != "__future__"):
lineno = item.lineno
break
pos += 1
imports = [ast.Import([alias], lineno=lineno, col_offset=0)
for alias in aliases]
mod.body[pos:pos] = imports
# Collect asserts.
nodes = collections.deque([mod])
while nodes:
node = nodes.popleft()
for name, field in ast.iter_fields(node):
if isinstance(field, list):
new = []
for i, child in enumerate(field):
if isinstance(child, ast.Assert):
# Transform assert.
new.extend(self.visit(child))
else:
new.append(child)
if isinstance(child, ast.AST):
nodes.append(child)
setattr(node, name, new)
elif (isinstance(field, ast.AST) and
# Don't recurse into expressions as they can't contain
# asserts.
not isinstance(field, ast.expr)):
nodes.append(field)
开发者ID:alemacgo,项目名称:pypy,代码行数:50,代码来源:rewrite.py
示例15: test_interleaved_ImportFrom
def test_interleaved_ImportFrom(self):
# Test prevention of statement merging.
import_from1 = ast.ImportFrom('X', [ast.alias('Y', None)], 1)
imp = ast.Import([ast.alias('X', None)])
# Separate by Import
import_from2 = ast.ImportFrom('X', [ast.alias('Z', None)], 1)
# Different level
import_from3 = ast.ImportFrom('X', [ast.alias('W', None)], 2)
# Different 'from' clause
import_from4 = ast.ImportFrom('Z', [ast.alias('Y', None)], 2)
module = ast.Module([import_from1, imp, import_from2, import_from3,
import_from4])
new_ast = self.transform.visit(module)
self.assertEqual(len(module.body), 5)
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:14,代码来源:test_mnfy.py
示例16: test_interleaved_statements
def test_interleaved_statements(self):
# Do not combine if something between the Import statements.
imp1 = ast.Import([ast.alias('X', None)])
imp2 = ast.Import([ast.alias('Y', None)])
from_import = ast.ImportFrom('Z', [ast.alias('W', None)], 0)
module = ast.Module([imp1, from_import, imp2])
new_ast = self.transform.visit(module)
self.assertEqual(len(new_ast.body), 3)
for given, expect in zip(new_ast.body,
(ast.Import, ast.ImportFrom, ast.Import)):
self.assertIsInstance(given, expect)
last_imp = new_ast.body[2]
self.assertEqual(len(last_imp.names), 1)
self.assertEqual(last_imp.names[0].name, 'Y')
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:14,代码来源:test_mnfy.py
示例17: new_nodes
def new_nodes(self):
nodes = []
# first turn all the from imports back into proper nodes
for (level, module), names in self.from_imports.iteritems():
for nm, asnm in sorted(names):
node = ast.ImportFrom(module=module, names=[ast.alias(name=nm, asname=asnm)], level=level)
nodes.append((self._node_sort_key(node), node))
# then build the normal imports again
for nm, asnm in self.imports:
node = ast.Import(names=[ast.alias(name=nm, asname=asnm)])
nodes.append((self._node_sort_key(node), node))
return nodes
开发者ID:public,项目名称:vim-sort-python-imports,代码行数:15,代码来源:sort_imports.py
示例18: visit_Module
def visit_Module(self, node):
super(TemplateCodeGenerator, self).visit_Module(node)
# Make sure we terminate the line printer
self.visit_Pass(None)
# Clear lines array for import visits
body = self.lines
self.lines = []
while self.defines:
name, node = self.defines.popitem()
assignment = ast.Assign(targets=[store(name)], value=node)
self.visit(assignment)
# Make sure we terminate the line printer
self.visit_Pass(None)
# 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.visit_Pass(None)
# Stich together lines
self.lines += defines + body
开发者ID:bshanks,项目名称:chameleon,代码行数:48,代码来源:codegen.py
示例19: visit_ImportFrom
def visit_ImportFrom(self, node):
for alias in node.names:
if alias.name == '*':
node.names.pop()
node.names.extend(ast.alias(fname, None)
for fname in modules[node.module])
return node
开发者ID:pythran-travis,项目名称:pythran,代码行数:7,代码来源:expand_import_all.py
示例20: make_importfrom_alias
def make_importfrom_alias(queue, body, context, name):
"""
Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of the IMPORT_FROM node to be popped.
Returns
-------
alias : ast.alias
Side Effects
------------
Consumes IMPORT_FROM and STORE_NAME instructions from queue.
"""
import_from, store = queue.popleft(), queue.popleft()
expect(import_from, instrs.IMPORT_FROM, "after IMPORT_NAME")
if not import_from.arg == name:
raise DecompilationError(
"IMPORT_FROM name mismatch. Expected %r, but got %s." % (
name, import_from,
)
)
return ast.alias(
name=name,
asname=store.arg if store.arg != name else None,
)
开发者ID:jcrist,项目名称:codetransformer,代码行数:35,代码来源:decompiler.py
注:本文中的ast.alias函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论