Python ast.alias() Examples

The following are 30 code examples of ast.alias(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: module_definitions.py    From pyt with GNU General Public License v2.0 6 votes vote down vote up
def __init__(
        self,
        local_module_definitions,
        name,
        parent_module_name,
        path
    ):
        self.module_definitions = local_module_definitions
        self.parent_module_name = parent_module_name
        self.path = path

        if parent_module_name:
            if isinstance(parent_module_name, ast.alias):
                self.name = parent_module_name.name + '.' + name
            else:
                self.name = parent_module_name + '.' + name
        else:
            self.name = name 
Example #2
Source File: module_definitions.py    From pyt with GNU General Public License v2.0 6 votes vote down vote up
def __init__(
        self,
        import_names=None,
        module_name=None,
        is_init=False,
        filename=None
    ):
        """Optionally set import names and module name.

        Module name should only be set when it is a normal import statement.
        """
        self.import_names = import_names
        # module_name is sometimes ast.alias or a string
        self.module_name = module_name
        self.is_init = is_init
        self.filename = filename
        self.definitions = list()
        self.classes = list()
        self.import_alias_mapping = dict() 
Example #3
Source File: sourceLoader.py    From Thespian with MIT License 6 votes vote down vote up
def visit_Import(self, node):  # Import(alias* names)
        newnames = []
        for A in node.names:
            firstName = A.name.partition('.')[0]
            if firstName in self._topnames:
                if A.asname is None:
                    # Normally "import foo.bar.bang" will cause foo to
                    # be added to globals.  This code converts "import
                    # x.y.z" to "import hash.x as x; import
                    # hash.x.y.z" to effect the same thing.
                    newnames.append(ast.copy_location(
                        ast.alias(self._sourceHashDot + firstName, firstName), A))
                    newnames.append(ast.copy_location(
                        ast.alias(self._sourceHashDot + A.name, None), A))
                else:
                    newnames.append(ast.copy_location(ast.alias(self._sourceHashDot + A.name, A.asname), A))
            else:
                newnames.append(A)
        return ast.copy_location(ast.Import(newnames), node) 
Example #4
Source File: gen.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __to_module(self):

		module_components = [
			ast.ImportFrom(module="ChromeController.transport",    names=[ast.alias('ChromeExecutionManager', None)], level=0),
			ast.ImportFrom(module="ChromeController.manager_base", names=[ast.alias('ChromeInterface',     None)], level=0),
			self.interface_class,
		]

		if sys.version_info >= (3, 8):
			mod = ast.Module(module_components, [], lineno=self.__get_line(), col_offset=1)
		else:
			mod = ast.Module(module_components, lineno=self.__get_line(), col_offset=1)

		mod = ast.fix_missing_locations(mod)

		return mod 
Example #5
Source File: scope_test.py    From pasta with Apache License 2.0 5 votes vote down vote up
def test_try_nested_imports(self):
    source = textwrap.dedent("""\
        try:
          import aaa
        except:
          import bbb
        finally:
          import ccc
        """)
    tree = ast.parse(source)
    nodes = tree.body

    node_aaa, node_bbb, node_ccc = ast_utils.find_nodes_by_type(tree, ast.alias)

    s = scope.analyze(tree)

    self.assertItemsEqual(s.names.keys(), {'aaa', 'bbb', 'ccc'})
    self.assertItemsEqual(s.external_references.keys(), {'aaa', 'bbb', 'ccc'})
    
    self.assertEqual(s.names['aaa'].definition, node_aaa)
    self.assertEqual(s.names['bbb'].definition, node_bbb)
    self.assertEqual(s.names['ccc'].definition, node_ccc)

    for ref in {'aaa', 'bbb', 'ccc'}:
      self.assertEqual(s.names[ref].reads, [],
                       'Expected no reads for %s' % ref) 
Example #6
Source File: analysis.py    From pyrs with MIT License 5 votes vote down vote up
def get_id(var):
        if isinstance(var, ast.alias):
            return var.name
        elif isinstance(var, ast.Name):
            return var.id
        elif isinstance(var, ast.arg):
            return var.arg 
Example #7
Source File: analysis.py    From pyrs with MIT License 5 votes vote down vote up
def get_id(var):
        if isinstance(var, ast.alias):
            return var.name
        elif isinstance(var, ast.Name):
            return var.id 
Example #8
Source File: test_build_ast.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def build_module():

	module_components = [
		# ast.ImportFrom(module="ChromeController.transport",    names=[ast.alias('ChromeSocketManager', None)], level=0),
		# ast.ImportFrom(module="ChromeController.manager_base", names=[ast.alias('ChromeInterface',     None)], level=0),
		build_ast_class(),
	]

	mod = ast.Module(module_components, lineno=1, col_offset=1)

	mod = ast.fix_missing_locations(mod)
	print("Module:", mod)
	return mod 
Example #9
Source File: python_util.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _apply_import(self, node):
        for name in node.names:
            if isinstance(name, ast.alias):
                self._imports.append(name.name) 
Example #10
Source File: translation.py    From mochi with MIT License 5 votes vote down vote up
def translate_import(self, exp):
        if len(exp) < 2:
            raise MochiSyntaxError(exp, self.filename)
        names = [ast.alias(name=import_sym.name,
                           asname=None,
                           lineno=import_sym.lineno,
                           col_offset=import_sym.col_offset) for import_sym in exp[1:]]
        return (ast.Import(names=names,
                           lineno=exp[0].lineno,
                           col_offset=exp[0].col_offset),), self.translate_ref(NONE_SYM)[1] 
Example #11
Source File: translation.py    From mochi with MIT License 5 votes vote down vote up
def translate_from(self, exp):
        if len(exp) < 3:
            raise MochiSyntaxError(exp, self.filename)
        names = [ast.alias(name=import_sym.name,
                           asname=None,
                           lineno=import_sym.lineno,
                           col_offset=import_sym.col_offset) for import_sym_names in exp[2:]
                                                             for import_sym in import_sym_names]
        return (ast.ImportFrom(module=exp[1].name,
                               names=names,
                               level=0,
                               lineno=exp[0].lineno,
                               col_offset=exp[0].col_offset),), self.translate_ref(NONE_SYM)[1] 
Example #12
Source File: flake8_mypy.py    From flake8-mypy with MIT License 5 votes vote down vote up
def visit_Import(self, node: ast.Import) -> None:
        for name in node.names:
            if (
                isinstance(name, ast.alias) and
                name.name == 'typing' or
                name.name.startswith('typing.')
            ):
                self.should_type_check = True
                break 
Example #13
Source File: analyzer.py    From chalice with Apache License 2.0 5 votes vote down vote up
def visit_Import(self, node):
        # type: (ast.Import) -> None
        for child in node.names:
            if isinstance(child, ast.alias):
                import_name = child.name
                if import_name == self._SDK_PACKAGE:
                    self._set_inferred_type_for_name(
                        import_name, Boto3ModuleType())
        self.generic_visit(node) 
Example #14
Source File: scope_test.py    From pasta with Apache License 2.0 5 votes vote down vote up
def test_if_nested_imports(self):
    source = textwrap.dedent("""\
        if a:
          import aaa
        elif b:
          import bbb
        else:
          import ccc
        """)
    tree = ast.parse(source)
    nodes = tree.body

    node_aaa, node_bbb, node_ccc = ast_utils.find_nodes_by_type(tree, ast.alias)

    s = scope.analyze(tree)

    self.assertItemsEqual(s.names.keys(), {'aaa', 'bbb', 'ccc', 'a', 'b'})
    self.assertItemsEqual(s.external_references.keys(), {'aaa', 'bbb', 'ccc'})
    
    self.assertEqual(s.names['aaa'].definition, node_aaa)
    self.assertEqual(s.names['bbb'].definition, node_bbb)
    self.assertEqual(s.names['ccc'].definition, node_ccc)

    self.assertIsNone(s.names['a'].definition)
    self.assertIsNone(s.names['b'].definition)

    for ref in {'aaa', 'bbb', 'ccc'}:
      self.assertEqual(s.names[ref].reads, [],
                       'Expected no reads for %s' % ref) 
Example #15
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_integer(self):
        # issue13436: Bad error message with invalid numeric values
        body = [ast.ImportFrom(module='time',
                               names=[ast.alias(name='sleep')],
                               level=None,
                               lineno=None, col_offset=None)]
        mod = ast.Module(body)
        with self.assertRaises(ValueError) as cm:
            compile(mod, 'test', 'exec')
        self.assertIn("invalid integer value: None", str(cm.exception)) 
Example #16
Source File: scope_test.py    From pasta with Apache License 2.0 5 votes vote down vote up
def test_functiondef_nested_imports(self):
    source = textwrap.dedent("""\
        def foo(bar):
          import aaa
        """)
    tree = ast.parse(source)
    nodes = tree.body

    node_aaa = ast_utils.find_nodes_by_type(tree, ast.alias)[0]

    s = scope.analyze(tree)

    self.assertItemsEqual(s.names.keys(), {'foo'})
    self.assertItemsEqual(s.external_references.keys(), {'aaa'}) 
Example #17
Source File: import_utils.py    From pasta with Apache License 2.0 5 votes vote down vote up
def split_import(sc, node, alias_to_remove):
  """Split an import node by moving the given imported alias into a new import.

  Arguments:
    sc: (scope.Scope) Scope computed on whole tree of the code being modified.
    node: (ast.Import|ast.ImportFrom) An import node to split.
    alias_to_remove: (ast.alias) The import alias node to remove. This must be a
      child of the given `node` argument.

  Raises:
    errors.InvalidAstError: if `node` is not appropriately contained in the tree
      represented by the scope `sc`.
  """
  parent = sc.parent(node)
  parent_list = None
  for a in ('body', 'orelse', 'finalbody'):
    if hasattr(parent, a) and node in getattr(parent, a):
      parent_list = getattr(parent, a)
      break
  else:
    raise errors.InvalidAstError('Unable to find list containing import %r on '
                                 'parent node %r' % (node, parent))

  idx = parent_list.index(node)
  new_import = copy.deepcopy(node)
  new_import.names = [alias_to_remove]
  node.names.remove(alias_to_remove)

  parent_list.insert(idx + 1, new_import)
  return new_import 
Example #18
Source File: import_utils.py    From pasta with Apache License 2.0 5 votes vote down vote up
def get_unused_import_aliases(tree, sc=None):
  """Get the import aliases that aren't used.

  Arguments:
    tree: (ast.AST) An ast to find imports in.
    sc: A scope.Scope representing tree (generated from scratch if not
    provided).

  Returns:
    A list of ast.alias representing imported aliases that aren't referenced in
    the given tree.
  """
  if sc is None:
    sc = scope.analyze(tree)
  unused_aliases = set()
  for node in ast.walk(tree):
    if isinstance(node, ast.alias):
      str_name = node.asname if node.asname is not None else node.name
      if str_name in sc.names:
        name = sc.names[str_name]
        if not name.reads:
          unused_aliases.add(node)
      else:
        # This happens because of https://github.com/google/pasta/issues/32
        logging.warning('Imported name %s not found in scope (perhaps it\'s '
                        'imported dynamically)', str_name)

  return unused_aliases 
Example #19
Source File: import_utils.py    From pasta with Apache License 2.0 5 votes vote down vote up
def remove_duplicates(tree, sc=None):
  """Remove duplicate imports, where it is safe to do so.

  This does NOT remove imports that create new aliases

  Arguments:
    tree: (ast.AST) An ast to modify imports in.
    sc: A scope.Scope representing tree (generated from scratch if not
    provided).

  Returns:
    Whether any changes were made.
  """
  if sc is None:
    sc = scope.analyze(tree)

  modified = False
  seen_names = set()
  for node in tree.body:
    if isinstance(node, (ast.Import, ast.ImportFrom)):
      for alias in list(node.names):
        import_node = sc.parent(alias)
        if isinstance(import_node, ast.Import):
          full_name = alias.name
        elif import_node.module:
          full_name = '%s%s.%s' % ('.' * import_node.level,
                                   import_node.module, alias.name)
        else:
          full_name = '%s%s' % ('.' * import_node.level, alias.name)
        full_name += ':' + (alias.asname or alias.name)
        if full_name in seen_names:
          remove_import_alias_node(sc, alias)
          modified = True
        else:
          seen_names.add(full_name)
  return modified 
Example #20
Source File: rename.py    From pasta with Apache License 2.0 5 votes vote down vote up
def _rename_name_in_importfrom(sc, node, old_name, new_name):
  if old_name == new_name:
    return False

  module_parts = node.module.split('.')
  old_parts = old_name.split('.')
  new_parts = new_name.split('.')

  # If just the module is changing, rename it
  if module_parts[:len(old_parts)] == old_parts:
    node.module = '.'.join(new_parts + module_parts[len(old_parts):])
    return True
    
  # Find the alias node to be changed
  for alias_to_change in node.names:
    if alias_to_change.name == old_parts[-1]:
      break
  else:
    return False

  alias_to_change.name = new_parts[-1]

  # Split the import if the package has changed
  if module_parts != new_parts[:-1]:
    if len(node.names) > 1:
      new_import = import_utils.split_import(sc, node, alias_to_change)
      new_import.module = '.'.join(new_parts[:-1])
    else:
      node.module = '.'.join(new_parts[:-1])

  return True 
Example #21
Source File: sourceLoader.py    From Thespian with MIT License 5 votes vote down vote up
def visit_ImportFrom(self, node):  # ImportFrom(identifier? module, alias* names, int? level)
        modname = (self._sourceHashDot + node.module) \
                  if node.level == 0 and node.module and node.module.partition('.')[0] in self._topnames \
                  else node.module
        return ast.copy_location(ast.ImportFrom(modname, node.names, node.level), node) 
Example #22
Source File: blocks.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_alias(self, node: ast.alias) -> None:
        """
        Visits aliases from ``import`` and ``from ... import`` block nodes.

        Raises:
            BlockAndLocalOverlapViolation

        """
        parent = cast(AnyImport, get_parent(node))
        import_name = {node.asname} if node.asname else {node.name}
        self._scope(parent, import_name, is_local=False)
        self._outer_scope(parent, import_name)
        self.generic_visit(node) 
Example #23
Source File: anutils.py    From Python-DevOps with MIT License 5 votes vote down vote up
def format_alias(x):
    """Return human-readable description of an ast.alias (used in Import and ImportFrom nodes)."""
    if not isinstance(x, ast.alias):
        raise TypeError('Can only format an ast.alias; got %s' % type(x))

    if x.asname is not None:
        return '%s as %s' % (x.name, x.asname)
    else:
        return '%s' % (x.name) 
Example #24
Source File: modules.py    From ansible-testing with GNU General Public License v3.0 5 votes vote down vote up
def _find_module_utils(self, main):
        linenos = []
        found_basic = False
        for child in self.ast.body:
            if isinstance(child, (ast.Import, ast.ImportFrom)):
                names = []
                try:
                    names.append(child.module)
                    if child.module.endswith('.basic'):
                        found_basic = True
                except AttributeError:
                    pass
                names.extend([n.name for n in child.names])

                if [n for n in names if n.startswith('ansible.module_utils')]:
                    linenos.append(child.lineno)

                    for name in child.names:
                        if (isinstance(name, ast.alias) and
                                name.name == 'basic'):
                            found_basic = True

        if not linenos:
            self.errors.append('Did not find a module_utils import')
        elif not found_basic:
            self.warnings.append('Did not find "ansible.module_utils.basic" '
                               'import')

        return linenos 
Example #25
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_integer(self):
        # issue13436: Bad error message with invalid numeric values
        body = [ast.ImportFrom(module='time',
                               names=[ast.alias(name='sleep')],
                               level=None,
                               lineno=None, col_offset=None)]
        mod = ast.Module(body)
        with self.assertRaises(ValueError) as cm:
            compile(mod, 'test', 'exec')
        self.assertIn("invalid integer value: None", str(cm.exception)) 
Example #26
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_importfrom(self):
        imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
        self.stmt(imp, "level less than -1")
        self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom") 
Example #27
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_bad_integer(self):
        # issue13436: Bad error message with invalid numeric values
        body = [ast.ImportFrom(module='time',
                               names=[ast.alias(name='sleep')],
                               level=None,
                               lineno=None, col_offset=None)]
        mod = ast.Module(body)
        with self.assertRaises(ValueError) as cm:
            compile(mod, 'test', 'exec')
        self.assertIn("invalid integer value: None", str(cm.exception)) 
Example #28
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_importfrom(self):
        imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
        self.stmt(imp, "level less than -1")
        self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom") 
Example #29
Source File: code_generator.py    From nni with MIT License 5 votes vote down vote up
def parse(code, nas_mode=None):
    """Annotate user code.
    Return annotated code (str) if annotation detected; return None if not.
    code: original user code (str),
    nas_mode: the mode of NAS given that NAS interface is used
    """
    try:
        ast_tree = ast.parse(code)
    except Exception:
        raise RuntimeError('Bad Python code')

    transformer = Transformer(nas_mode)
    try:
        transformer.visit(ast_tree)
    except AssertionError as exc:
        raise RuntimeError('%d: %s' % (ast_tree.last_line, exc.args[0]))

    if not transformer.annotated:
        return None

    last_future_import = -1
    import_nni = ast.Import(names=[ast.alias(name='nni', asname=None)])
    nodes = ast_tree.body
    for i, _ in enumerate(nodes):
        if type(nodes[i]) is ast.ImportFrom and nodes[i].module == '__future__':
            last_future_import = i
    nodes.insert(last_future_import + 1, import_nni)
    # enas, oneshot and darts modes for tensorflow need tensorflow module, so we import it here
    if nas_mode in ['enas_mode', 'oneshot_mode', 'darts_mode']:
        import_tf = ast.Import(names=[ast.alias(name='tensorflow', asname=None)])
        nodes.insert(last_future_import + 1, import_tf)

    return astor.to_source(ast_tree) 
Example #30
Source File: module_definitions.py    From pyt with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        module = 'NoModuleName'
        if self.module_name:
            module = self.module_name

        if self.definitions:
            if isinstance(module, ast.alias):
                return (
                    'Definitions: "' + '", "'
                    .join([str(definition) for definition in self.definitions]) +
                    '" and module_name: ' + module.name +
                    ' and filename: ' + str(self.filename) +
                    ' and is_init: ' + str(self.is_init) + '\n')
            return (
                'Definitions: "' + '", "'
                .join([str(definition) for definition in self.definitions]) +
                '" and module_name: ' + module +
                ' and filename: ' + str(self.filename) +
                ' and is_init: ' + str(self.is_init) + '\n')
        else:
            if isinstance(module, ast.alias):
                return (
                    'import_names is ' + str(self.import_names) +
                    ' No Definitions, module_name: ' + str(module.name) +
                    ' and filename: ' + str(self.filename) +
                    ' and is_init: ' + str(self.is_init) + '\n')
            return (
                'import_names is ' + str(self.import_names) +
                ' No Definitions, module_name: ' + str(module) +
                ' and filename: ' + str(self.filename) +
                ' and is_init: ' + str(self.is_init) + '\n')