def single_import(path, imp_as):
    """Generate import statements from a fully qualified import and the name to bind it to."""
    out = []

    parts = path.split("./")  # denotes from ... import ...
    if len(parts) == 1:
        imp_from, imp = None, parts[0]
    else:
        imp_from, imp = parts

    if imp == imp_as:
        imp_as = None
    elif imp.endswith("." + imp_as):
        if imp_from is None:
            imp_from = ""
        imp_from += imp.rsplit("." + imp_as, 1)[0]
        imp, imp_as = imp_as, None

    if imp_from is None and imp == "sys":
        out.append((imp_as if imp_as is not None else imp) + " = _coconut_sys")
    elif imp_as is not None and "." in imp_as:
        fake_mods = imp_as.split(".")
        out.append(import_stmt(imp_from, imp, import_as_var))
        for i in range(1, len(fake_mods)):
            mod_name = ".".join(fake_mods[:i])
            out.extend((
                "try:",
                openindent + mod_name,
                closeindent + "except:",
                openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")',
                closeindent + "else:",
                openindent + "if not _coconut.isinstance(" + mod_name + ", _coconut.types.ModuleType):",
                openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")' + closeindent * 2,
            ))
        out.append(".".join(fake_mods) + " = " + import_as_var)
    else:
        out.append(import_stmt(imp_from, imp, imp_as))

    return out
def single_import ( path , imp_as ) : out = [ ] parts = path . split ( "./" ) if len ( parts ) == 1 : imp_from , imp = None , parts [ 0 ] else : imp_from , imp = parts if imp == imp_as : imp_as = None elif imp . endswith ( "." + imp_as ) : if imp_from is None : imp_from = "" imp_from += imp . rsplit ( "." + imp_as , 1 ) [ 0 ] imp , imp_as = imp_as , None if imp_from is None and imp == "sys" : out . append ( ( imp_as if imp_as is not None else imp ) + " = _coconut_sys" ) elif imp_as is not None and "." in imp_as : fake_mods = imp_as . split ( "." ) out . append ( import_stmt ( imp_from , imp , import_as_var ) ) for i in range ( 1 , len ( fake_mods ) ) : mod_name = "." . join ( fake_mods [ : i ] ) out . extend ( ( "try:" , openindent + mod_name , closeindent + "except:" , openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")' , closeindent + "else:" , openindent + "if not _coconut.isinstance(" + mod_name + ", _coconut.types.ModuleType):" , openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")' + closeindent * 2 , ) ) out . append ( "." . join ( fake_mods ) + " = " + import_as_var ) else : out . append ( import_stmt ( imp_from , imp , imp_as ) ) return out
Generate import statements from a fully qualified import and the name to bind it to.