Using relative import in both Python 2 and Python 3
167524
def _rel_import(module, tgt):
    """"""
    try:
        exec("from ." + module + " import " + tgt, globals(), locals())
    except SyntaxError:
        # On Python < 2.5 relative import cause syntax error
        exec("from " + module + " import " + tgt, globals(), locals())
    except (ValueError, SystemError):
        # relative import in non-package, try absolute
        exec("from " + module + " import " + tgt, globals(), locals())
    return eval(tgt)
670978
def import_file(name, loc):
    
    loc = path2str(loc)
    if is_python_pre_3_5:
        import imp

        return imp.load_source(name, loc)
    else:
        import importlib.util

        spec = importlib.util.spec_from_file_location(name, str(loc))
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        return module
6076
def my_import(name, path=None):
    """"""

    # Documentation for importlib says this may be needed to pick up
    # modules created after the program has started
    if hasattr(importlib, 'invalidate_caches'):
        # python 3.3+
        importlib.invalidate_caches()

    if path is not None:
        directory, src_file = os.path.split(path)

        # TODO: use the importlib.util machinery
        sys.path.insert(0, directory)
        try:
            mod = importlib.import_module(name)
        finally:
            sys.path.pop(0)

    else:
        mod = importlib.import_module(name)

    return mod
861792
def _get_relative_pythonpath(self):
        """"""
        # Workaround to replace os.path.relpath (new in Python v2.6):
        offset = len(self.root_path)+len(os.pathsep)
        return [path[offset:] for path in self.pythonpath]
1132792
def import_module(module):  # pylint: disable=R0201
        
        if isinstance(module, list):
            all_modules = module
        else:
            all_modules = [module]
        for mod in all_modules:
            globals()[mod] = __import__(mod.strip())
796679
def __recursive_import(module_name):
    
    names = module_name.split(".")
    path = None
    module = None
    while len(names) > 0:
        if module:
            path = module.__path__
        name = names.pop(0)
        (module_file, pathname, description) = imp.find_module(name, path)
        module = imp.load_module(name, module_file, pathname, description)
    return module
857007
def import_classes(name, currmodule):
    # type: (unicode, unicode) -> Any
    """"""
    target = None

    # import class or module using currmodule
    if currmodule:
        target = try_import(currmodule + '.' + name)

    # import class or module without currmodule
    if target is None:
        target = try_import(name)

    if target is None:
        raise InheritanceException(
            'Could not import class or module %r specified for '
            'inheritance diagram' % name)

    if inspect.isclass(target):
        # If imported object is a class, just return it
        return [target]
    elif inspect.ismodule(target):
        # If imported object is a module, return classes defined on it
        classes = []
        for cls in target.__dict__.values():
            if inspect.isclass(cls) and cls_is_in_module(cls, mod=target):
                classes.append(cls)
        return classes
    raise InheritanceException('%r specified for inheritance diagram is '
                               'not a class or module' % name)
1338456
def import_file(filename, name=None):
    
    # Specifying a traditional dot-separated fully qualified name here
    # results in a number of "Parent module 'astropy' not found while
    # handling absolute import" warnings.  Using the same name, the
    # namespaces of the modules get merged together.  So, this
    # generates an underscore-separated name which is more likely to
    # be unique, and it doesn't really matter because the name isn't
    # used directly here anyway.
    mode = 'r'

    if name is None:
        basename = os.path.splitext(filename)[0]
        name = '_'.join(os.path.relpath(basename).split(os.sep)[1:])

    if not os.path.exists(filename):
        raise ImportError('Could not import file {0}'.format(filename))

    if import_machinery:
        loader = import_machinery.SourceFileLoader(name, filename)
        mod = loader.load_module()
    else:
        with open(filename, mode) as fd:
            mod = imp.load_module(name, fd, filename, ('.py', mode, 1))

    return mod
1183021
def _at_dump_imports(self, calculator, rule, scope, block):
        
        sys.stderr.write("%s\n" % repr(rule.namespace._imports))
676159
def import_modules(names, src, dst):
    """"""
    for name in names:
        module = importlib.import_module(src + '.' + name)
        setattr(sys.modules[dst], name, module)
79545
def __get_from_imports(import_tuples):
    
    from_imports = [(tup[0], tup[1]) for tup in import_tuples
                    if tup[1] is not None and len(tup[1]) > 0]
    return from_imports
1321207
def _import_module(module_name, warn=True, prefix='_py_', ignore='_'):
    
    try:
        module = __import__(module_name)
    except ImportError:
        if warn:
            warnings.warn("Failed to import module " + module_name)
    else:
        for attr in dir(module):
            if ignore and attr.startswith(ignore):
                continue
            if prefix:
                if attr in globals():
                    globals()[prefix + attr] = globals()[attr]
                elif warn:
                    warnings.warn("No Python implementation of " + attr)
            globals()[attr] = getattr(module, attr)
        return True
162056
def universal_import(imports, imp_from=None, target=""):
    """"""
    importmap = []  # [((imp | old_imp, imp, version_check), imp_as), ...]
    for imps in imports:
        if len(imps) == 1:
            imp, imp_as = imps[0], imps[0]
        else:
            imp, imp_as = imps
        if imp_from is not None:
            imp = imp_from + "./" + imp  # marker for from ... import ...
        old_imp = None
        path = imp.split(".")
        for i in reversed(range(1, len(path) + 1)):
            base, exts = ".".join(path[:i]), path[i:]
            clean_base = base.replace("/", "")
            if clean_base in py3_to_py2_stdlib:
                old_imp, version_check = py3_to_py2_stdlib[clean_base]
                if exts:
                    old_imp += "."
                    if "/" in base and "/" not in old_imp:
                        old_imp += "/"  # marker for from ... import ...
                    old_imp += ".".join(exts)
                break
        if old_imp is None:
            paths = (imp,)
        elif not target:  # universal compatibility
            paths = (old_imp, imp, version_check)
        elif get_target_info_len2(target) >= version_check:  # if lowest is above, we can safely use new
            paths = (imp,)
        elif target.startswith("2"):  # "2" and "27" can safely use old
            paths = (old_imp,)
        elif get_target_info(target) < version_check:  # "3" should be compatible with all 3+
            paths = (old_imp, imp, version_check)
        else:  # "35" and above can safely use new
            paths = (imp,)
        importmap.append((paths, imp_as))

    stmts = []
    for paths, imp_as in importmap:
        if len(paths) == 1:
            more_stmts = single_import(paths[0], imp_as)
            stmts.extend(more_stmts)
        else:
            first, second, version_check = paths
            stmts.append("if _coconut_sys.version_info < " + str(version_check) + ":")
            first_stmts = single_import(first, imp_as)
            first_stmts[0] = openindent + first_stmts[0]
            first_stmts[-1] += closeindent
            stmts.extend(first_stmts)
            stmts.append("else:")
            second_stmts = single_import(second, imp_as)
            second_stmts[0] = openindent + second_stmts[0]
            second_stmts[-1] += closeindent
            stmts.extend(second_stmts)
    return "\n".join(stmts)
49698
def _import(self, name):
        '''  '''
        mod = __import__(name)
        components = name.split('.')
        for comp in components[1:]:
            mod = getattr(mod, comp)
        return mod
1169082
function relativePath(file1, file2) {
  var file1Dirname = path.dirname(file1);
  var file2Dirname = path.dirname(file2);

  if (file1Dirname !== file2Dirname) {
    return path.relative(file1Dirname, file2Dirname);
  }
  return '';
}
651050
def get_imported_module_from_file(file_path):
        
        if p_compat.is_py3:
            imported_module = importlib.machinery.SourceFileLoader('module_name', file_path).load_module()
        elif p_compat.is_py2:
            imported_module = imp.load_source('module_name', file_path)
        else:
            raise RuntimeError("Neither Python 3 nor Python 2.")
    
        return imported_module
1089487
def relative_to_contrib(diff, project):
    
    path = pathlib.Path(diff.b_path)
    contrib_path = project.contrib_module_path
    return path.relative_to(contrib_path)