Turns `import a, b` into `import a` and `import b`
346125
def separate_comma_imports(partitions):
    """"""
    def _inner():
        for partition in partitions:
            if partition.code_type is CodeType.IMPORT:
                import_obj = import_obj_from_str(partition.src)
                if import_obj.has_multiple_imports:
                    for new_import_obj in import_obj.split_imports():
                        yield CodePartition(
                            CodeType.IMPORT, new_import_obj.to_text(),
                        )
                else:
                    yield partition
            else:
                yield partition

    return list(_inner())
1075513
def get_imported_modules(cells, nb_module_name=''):
    ""
    module_names = get_top_level_modules()
    nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell['source']) if cell['cell_type'] == 'code']
    parts = nb_module_name.split('.')
    parent_modules = ['.'.join(parts[:(x+1)]) for x in range_of(parts)] # Imports parent modules - a.b.c = [a, a.b, a.b.c]
    all_modules = module_names + nb_imports + parent_modules
    mods = [import_mod(m, ignore_errors=True) for m in all_modules]
    return [m for m in mods if m is not None]
1107649
def import_from(module, name):
    '''
    
    '''
    module = importlib.import_module(module)
    return getattr(module, name)
151016
def _merge_a_into_b(self, a, b):
        
        from easydict import EasyDict as edict
        if type(a) is not edict:
            return

        for k, v in a.items():
            # a must specify keys that are in b
            if k not in b:
                raise KeyError('{} is not a valid config key'.format(k))

            # the types must match, too
            old_type = type(b[k])
            if old_type is not type(v):
                if isinstance(b[k], np.ndarray):
                    v = np.array(v, dtype=b[k].dtype)
                else:
                    raise ValueError(('Type mismatch ({} vs. {}) '
                                      'for config key: {}').format(type(b[k]),
                                                                   type(v), k))

            # recursively merge dicts
            if type(v) is edict:
                try:
                    self._merge_a_into_b(a[k], b[k])
                except:
                    print('Error under config key: {}'.format(k))
                    raise
            else:
                b[k] = v
        return b
17795
def __push_import_modules(self):
        
        for module in self.__import_modules:
            sys.modules[module.__name__] = module
989425
def append_if_local_or_in_imports(self, definition):
        
        if isinstance(definition, LocalModuleDefinition):
            self.definitions.append(definition)
        elif self.import_names == ["*"]:
            self.definitions.append(definition)
        elif self.import_names and definition.name in self.import_names:
            self.definitions.append(definition)
        elif (self.import_alias_mapping and definition.name in
              self.import_alias_mapping.values()):
            self.definitions.append(definition)

        if definition.parent_module_name:
            self.definitions.append(definition)

        if definition.node not in project_definitions:
            project_definitions[definition.node] = definition
478090
def import_from(name):
    
    obj = name
    if isinstance(name, str) and len(name):
        try:
            obj = locate(name)
            assert obj is not None
        except (AttributeError, TypeError, AssertionError, ErrorDuringImport):
            try:
                name = name.split(".")
                attr = name[-1]
                name = ".".join(name[:-1])
                mod = importlib.import_module(name)
                obj = getattr(mod, attr)
            except (SyntaxError, AttributeError, ImportError, ValueError):
                try:
                    name = name.split(".")
                    attr_sup = name[-1]
                    name = ".".join(name[:-1])
                    mod = importlib.import_module(name)
                    obj = getattr(getattr(mod, attr_sup), attr)
                except:
                    # We give up.
                    pass

    obj = unwrap_obj(obj)
    return obj
175227
def iter_import_chunks(self):
    """"""
    chunk = []
    last_line = None
    for leaf in self.python_file.tree.body:
      if isinstance(leaf, (ast.Import, ast.ImportFrom)):
        # we've seen previous imports but this import is not in the same chunk
        if last_line and leaf.lineno != last_line[1]:
          yield chunk
          chunk = [leaf]
        # we've either not seen previous imports or this is part of the same chunk
        elif not last_line or last_line and leaf.lineno == last_line[1]:
          chunk.append(leaf)
        last_line = self.python_file.logical_lines[leaf.lineno]
    if chunk:
      yield chunk
172271
def build_import_pattern(mapping1, mapping2):
    
    """
    # py3k: urllib.request, py2k: ('urllib2', 'urllib')
    yield from_import % (all_modules_subpattern())
    for py3k, py2k in mapping1.items():
        name, attr = py3k.split(u'.')
        s_name = simple_name % (name)
        s_attr = simple_attr % (attr)
        d_name = dotted_name % (s_name, s_attr)
        yield name_import % (d_name)
        yield power_twoname % (s_name, s_attr)
        if attr == u'__init__':
            yield name_import % (s_name)
            yield power_onename % (s_name)
        yield name_import_rename % (d_name)
        yield from_import_rename % (s_name, s_attr, s_attr, s_attr, s_attr)
133439
def swap(self, a, b):
        
        self.mem[a], self.mem[b] = self.mem[b], self.mem[a]
        self.asm[a], self.asm[b] = self.asm[b], self.asm[a]
655668
function generateImportDeclaration(stmt, semicolon) {
        var result, cursor;

        // If no ImportClause is present,
        // this should be `import ModuleSpecifier` so skip `from`
        // ModuleSpecifier is StringLiteral.
        if (stmt.specifiers.length === 0) {
            // import ModuleSpecifier ;
            return [
                'import',
                space,
                // ModuleSpecifier
                generateExpression(stmt.source, {
                    precedence: Precedence.Sequence,
                    allowIn: true,
                    allowCall: true
                }),
                semicolon
            ];
        }

        // import ImportClause FromClause ;
        result = [
            'import'
        ];
        cursor = 0;

        // ImportedBinding
        if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
            result = join(result, [
                    generateExpression(stmt.specifiers[cursor], {
                        precedence: Precedence.Sequence,
                        allowIn: true,
                        allowCall: true
                    })
            ]);
            ++cursor;
        }

        if (stmt.specifiers[cursor]) {
            if (cursor !== 0) {
                result.push(',');
            }

            if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
                // NameSpaceImport
                result = join(result, [
                        space,
                        generateExpression(stmt.specifiers[cursor], {
                            precedence: Precedence.Sequence,
                            allowIn: true,
                            allowCall: true
                        })
                ]);
            } else {
                // NamedImports
                result.push(space + '{');

                if ((stmt.specifiers.length - cursor) === 1) {
                    // import { ... } from "...";
                    result.push(space);
                    result.push(generateExpression(stmt.specifiers[cursor], {
                        precedence: Precedence.Sequence,
                        allowIn: true,
                        allowCall: true
                    }));
                    result.push(space + '}' + space);
                } else {
                    // import {
                    //    ...,
                    //    ...,
                    // } from "...";
                    withIndent(function (indent) {
                        var i, iz;
                        result.push(newline);
                        for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
                            result.push(indent);
                            result.push(generateExpression(stmt.specifiers[i], {
                                precedence: Precedence.Sequence,
                                allowIn: true,
                                allowCall: true
                            }));
                            if (i + 1 < iz) {
                                result.push(',' + newline);
                            }
                        }
                    });
                    if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                        result.push(newline);
                    }
                    result.push(base + '}' + space);
                }
            }
        }

        result = join(result, [
            'from' + space,
            // ModuleSpecifier
            generateExpression(stmt.source, {
                precedence: Precedence.Sequence,
                allowIn: true,
                allowCall: true
            }),
            semicolon
        ]);
        return result;
    }
530121
def make_import_tuples(module_path, exclude_modnames=[]):
    
    from utool import util_path
    kwargs = dict(private=False, full=False)
    module_list  = util_path.ls_modulefiles(module_path, noext=True, **kwargs)
    package_list = util_path.ls_moduledirs(module_path, **kwargs)
    exclude_set = set(exclude_modnames)
    module_import_tuples = [(modname, None) for modname in module_list
                            if modname not in exclude_set]
    package_import_tuples = [(modname, None, True)  for modname in package_list
                            if modname not in exclude_set]
    import_tuples = (module_import_tuples + package_import_tuples)
    return import_tuples
676159
def import_modules(names, src, dst):
    """"""
    for name in names:
        module = importlib.import_module(src + '.' + name)
        setattr(sys.modules[dst], name, module)
128135
def import_modules(modules, safe=True):
    '''
    '''
    all = []
    for mname in modules:
        if mname.endswith('.*'):
            to_load = expand_star(mname)
        else:
            to_load = [mname]
        for module in to_load:
            try:
                all.append(import_module(module))
            except ImportError:
                if not safe:
                    raise
    return all
980066
def _process_instr_import_name(instr, queue, stack, body, context):
    
    # 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'")
769703
function parseImportLine (line) {
  if (IS_IMPORT.test(line)) {
    // could be either depending on whether default import was before or after named imports
    const [, default0, named, default1] = IMPORT.exec(line)
    const defaultImport = default0 || default1
    const namedImports = []
    if (named) {
      let next
      while ((next = NAMED_IMPORTS.exec(named)) != null) {
        const [, src, importedAs] = next
        namedImports.push([src, importedAs || src]) // if no alternate name, use default name
      }
    }

    return [defaultImport, namedImports]
  } else {
    return null
  }
}
678402
def importobj(modpath, attrname):
    """"""
    module = __import__(modpath, None, None, ['__doc__'])
    if not attrname:
        return module

    retval = module
    names = attrname.split(".")
    for x in names:
        retval = getattr(retval, x)
    return retval