Import string format module, e.g. 'uliweb.orm' or an object
    return module object and object
197893
def import_mod_attr(path):
    
    import inspect

    if isinstance(path, (str, unicode)):
        v = path.split(':')
        if len(v) == 1:
            module, func = path.rsplit('.', 1)
        else:
            module, func = v
        mod = __import__(module, fromlist=['*'])
        f = mod
        for x in func.split('.'):
            try:
                f = getattr(f, x)
            except:
                raise AttributeError("Get %s attribute according %s error" % (x, path))
    else:
        f = path
        mod = inspect.getmodule(path)
    return mod, f
797987
def perform_import(val):
    
    if val is None:
        return None
    elif isinstance(val, str):
        return import_from_string(val)
    elif isinstance(val, (list, tuple)):
        return [import_from_string(item) for item in val]
    return val
1124321
def import_string(dotted_path: str) -> ModuleType:
    
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        msg = "%s doesn't look like a module path" % dotted_path
        raise ImportError(msg)

    module = import_module(module_path)

    try:
        return getattr(module, class_name)
    except AttributeError:
        msg = 'Module "%s" does not define a "%s" attribute/class' % (
            module_path, class_name)
        raise ImportError(msg)
727988
def load_object(name):
    """"""

    if "." not in name:
        raise Exception('load object need module.object')

    module_name, object_name = name.rsplit('.', 1)
    if six.PY2:
        module = __import__(module_name, globals(), locals(), [utf8(object_name)], -1)
    else:
        module = __import__(module_name, globals(), locals(), [object_name])
    return getattr(module, object_name)
970160
function getLitmusForModule (module) {

    if (isLitmus(module)) {
        return module;
    }

    if (module.test && isLitmus(module.test)) {
        return module.test;
    }

    throw new Error('litmus: expected module to export litmus.Test or litmus.Suite');
}
38011
def arbitrary_object_to_string(a_thing):
    """"""
    # is it None?
    if a_thing is None:
        return ''
    # is it already a string?
    if isinstance(a_thing, six.string_types):
        return a_thing
    if six.PY3 and isinstance(a_thing, six.binary_type):
        try:
            return a_thing.decode('utf-8')
        except UnicodeDecodeError:
            pass
    # does it have a to_str function?
    try:
        return a_thing.to_str()
    except (AttributeError, KeyError, TypeError):
        # AttributeError - no to_str function?
        # KeyError - DotDict has no to_str?
        # TypeError - problem converting
        # nope, no to_str function
        pass
    # is this a type proxy?
    try:
        return arbitrary_object_to_string(a_thing.a_type)
    except (AttributeError, KeyError, TypeError):
        #
        # nope, no a_type property
        pass
    # is it a built in?
    try:
        return known_mapping_type_to_str[a_thing]
    except (KeyError, TypeError):
        # nope, not a builtin
        pass
    # is it something from a loaded module?
    try:
        if a_thing.__module__ not in ('__builtin__', 'builtins', 'exceptions'):
            if a_thing.__module__ == "__main__":
                module_name = (
                    sys.modules['__main__']
                    .__file__[:-3]
                    .replace('/', '.')
                    .strip('.')
                )
            else:
                module_name = a_thing.__module__
            return "%s.%s" % (module_name, a_thing.__name__)
    except AttributeError:
        # nope, not one of these
        pass
    # maybe it has a __name__ attribute?
    try:
        return a_thing.__name__
    except AttributeError:
        # nope, not one of these
        pass
    # punt and see what happens if we just cast it to string
    return str(a_thing)
1181853
def import_module(module_name):
    """"""
    import sys, os
    import importlib
    sys.path.append(os.path.dirname(__file__))
    return importlib.import_module(module_name)
846325
def import_util(imp):
    '''
    
    '''

    mod_name, obj_name = imp.rsplit('.', 1)
    mod = importlib.import_module(mod_name)
    return getattr(mod, obj_name)
23522
def format_string(m, l, capture, is_bytes):
    """"""

    for fmt_type, value in capture[1:]:
        if fmt_type == FMT_ATTR:
            # Attribute
            l = getattr(l, value)
        elif fmt_type == FMT_INDEX:
            # Index
            l = l[value]
        elif fmt_type == FMT_CONV:
            if is_bytes:
                # Conversion
                if value in ('r', 'a'):
                    l = repr(l).encode('ascii', 'backslashreplace')
                elif value == 's':
                    # If the object is not string or byte string already
                    l = _to_bstr(l)
            else:
                # Conversion
                if value == 'a':
                    l = ascii(l)
                elif value == 'r':
                    l = repr(l)
                elif value == 's':
                    # If the object is not string or byte string already
                    l = str(l)
        elif fmt_type == FMT_SPEC:
            # Integers and floats don't have an explicit 's' format type.
            if value[3] and value[3] == 's':
                if isinstance(l, int):  # pragma: no cover
                    raise ValueError("Unknown format code 's' for object of type 'int'")
                if isinstance(l, float):  # pragma: no cover
                    raise ValueError("Unknown format code 's' for object of type 'float'")

            # Ensure object is a byte string
            l = _to_bstr(l) if is_bytes else str(l)

            spec_type = value[1]
            if spec_type == '^':
                l = l.center(value[2], value[0])
            elif spec_type == ">":
                l = l.rjust(value[2], value[0])
            else:
                l = l.ljust(value[2], value[0])

    # Make sure the final object is a byte string
    return _to_bstr(l) if is_bytes else str(l)
710843
def _format_str(string):
    """"""
    if isinstance(string, _STRTYPES):
        if _IS_PYTHON3:
            array = _array.array('I')
            array.frombytes(string.encode(_utf32_codec))
        else: # Python 2
            if isinstance(string, unicode):
                array = _array.array(b'I')
                array.fromstring(string.encode(_utf32_codec))
            else:
                array = _array.array(b'B')
                array.fromstring(string)
        return array
    return string
594412
def str_to_python_object(input_str):
    
    if not input_str:
        return None
    if six.PY3 and isinstance(input_str, six.binary_type):
        input_str = to_str(input_str)
    if not isinstance(input_str, six.string_types):
        # gosh, we didn't get a string, we can't convert anything but strings
        # we're going to assume that what we got is actually what was wanted
        # as the output
        return input_str
    input_str = str_quote_stripper(input_str)
    if '.' not in input_str and input_str in known_mapping_str_to_type:
        return known_mapping_str_to_type[input_str]
    parts = [x.strip() for x in input_str.split('.') if x.strip()]
    try:
        try:
            # first try as a complete module
            package = __import__(input_str)
        except ImportError:
            # it must be a class from a module
            if len(parts) == 1:
                # since it has only one part, it must be a class from __main__
                parts = ('__main__', input_str)
            package = __import__('.'.join(parts[:-1]), globals(), locals(), [])
        obj = package
        for name in parts[1:]:
            obj = getattr(obj, name)
        return obj
    except AttributeError as x:
        raise CannotConvertError("%s cannot be found" % input_str)
    except ImportError as x:
        raise CannotConvertError(str(x))
1006273
def _import_type(line: str) -> Optional[str]:
        """"""
        if "isort:skip" in line or "NOQA" in line:
            return None
        elif line.startswith('import '):
            return "straight"
        elif line.startswith('from '):
            return "from"
615569
def generate_import_from(module_, names):
        
        regular_names = [n for n in names if "::" not in n]
        as_names = [n for n in names if "::" in n]

        line = ""
        if len(regular_names) > 0:
            slots = {"m": module_, "n": ", ".join(sorted(regular_names))}
            line = "from %(m)s import %(n)s" % slots
            if len(line) > LINE_LENGTH_LIMIT:
                slots["n"] = INDENT + (",\n" + INDENT).join(sorted(regular_names)) + ","
                line = "from %(m)s import (\n%(n)s\n)" % slots
            if len(as_names) > 0:
                line += "\n"

        for as_name in as_names:
            a, n = as_name.split("::")
            line += "from %(m)s import %(n)s as %(a)s" % {"m": module_, "n": n, "a": a}
        return line
645512
def get_module_imports_on_top_of_file(source, import_line_index):
    
    def is_string_literal(line):
        if line[0] in 'uUbB':
            line = line[1:]
        if line and line[0] in 'rR':
            line = line[1:]
        return line and (line[0] == '"' or line[0] == "'")

    def is_future_import(line):
        nodes = ast.parse(line)
        for n in nodes.body:
            if isinstance(n, ast.ImportFrom) and n.module == '__future__':
                return True
        return False

    allowed_try_keywords = ('try', 'except', 'else', 'finally')
    in_docstring = False
    docstring_kind = '"""'
    for cnt, line in enumerate(source):
        if not in_docstring:
            m = DOCSTRING_START_REGEX.match(line.lstrip())
            if m is not None:
                in_docstring = True
                docstring_kind = m.group('kind')
                remain = line[m.end(): m.endpos].rstrip()
                if remain[-3:] == docstring_kind:  # one line doc
                    in_docstring = False
                continue
        if in_docstring:
            if line.rstrip()[-3:] == docstring_kind:
                in_docstring = False
            continue

        if not line.rstrip():
            continue
        elif line.startswith('#'):
            continue

        if line.startswith('import ') or line.startswith('from '):
            if cnt == import_line_index or is_future_import(line):
                continue
            return cnt
        elif pycodestyle.DUNDER_REGEX.match(line):
            continue
        elif any(line.startswith(kw) for kw in allowed_try_keywords):
            continue
        elif is_string_literal(line):
            return cnt
        else:
            return cnt
    return 0
1166135
def import_class(import_str):
    """"""
    mod_str, _sep, class_str = import_str.rpartition(".")
    __import__(mod_str)
    return getattr(sys.modules[mod_str], class_str)
1042371
def _str_to_fn(self, fn_as_str):
        
        if not isinstance(fn_as_str, str):
            return fn_as_str

        path, _, function = fn_as_str.rpartition('.')
        module = importlib.import_module(path)
        return getattr(module, function)
200926
def _str_to_type_from_member_module(cls, module_, string):
        

        module_name_short, class_name = string.split(cls._DELIMITER_MODULE)
        members = inspect.getmembers(module_, inspect.ismodule)

        for name, module_member in members:
            if module_name_short == name:
                return getattr(module_member, class_name)

        error_message = cls._ERROR_COULD_NOT_FIND_CLASS.format(string)

        raise exception.BunqException(error_message)