Take a full path to a python method or class, for example
    mypkg.subpkg.method and return the method or class (after importing the
    required packages)
768201
def get_function(pkgpath):
    
    # Extract the module and function name from pkgpath
    elems = pkgpath.split('.')
    if len(elems) <= 1:
        raise PyMacaronCoreException("Path %s is too short. Should be at least module.func." % elems)
    func_name = elems[-1]
    func_module = '.'.join(elems[0:-1])

    # Load the function's module and get the function
    try:
        m = import_module(func_module)
        f = getattr(m, func_name)
        return f
    except Exception as e:
        t = traceback.format_exc()
        raise PyMacaronCoreException("Failed to import %s: %s\nTrace:\n%s" % (pkgpath, str(e), t))
560011
def importfile(filename):
    
    pkg = packageFromPath(filename, includeModule=True)
    root = packageRootPath(filename)

    if root not in sys.path:
        sys.path.insert(0, root)

    __import__(pkg)
    return sys.modules[pkg]
733285
def _get_module_via_parent_enumeration(self, fullname):
        
        if fullname not in sys.modules:
            # Don't attempt this unless a module really exists in sys.modules,
            # else we could return junk.
            return

        pkgname, _, modname = str_rpartition(to_text(fullname), u'.')
        pkg = sys.modules.get(pkgname)
        if pkg is None or not hasattr(pkg, '__file__'):
            return

        pkg_path = os.path.dirname(pkg.__file__)
        try:
            fp, path, ext = imp.find_module(modname, [pkg_path])
            try:
                path = self._py_filename(path)
                if not path:
                    fp.close()
                    return

                source = fp.read()
            finally:
                if fp:
                    fp.close()

            if isinstance(source, mitogen.core.UnicodeType):
                # get_source() returns "string" according to PEP-302, which was
                # reinterpreted for Python 3 to mean a Unicode string.
                source = source.encode('utf-8')
            return path, source, False
        except ImportError:
            e = sys.exc_info()[1]
            LOG.debug('imp.find_module(%r, %r) -> %s', modname, [pkg_path], e)
657885
def get_package_path(name):
    
    name = name.lower()  # use lowercase version to be safe
    # Here we're importing the module just to find it. This is worryingly
    # indirect, but it's otherwise very difficult to find the package.
    pkg = importlib.import_module(name)
    return Path(pkg.__file__).parent
228168
def class_path(cls):
    """"""
    if cls.__module__ == '__main__':
        path = None
    else:
        path = os.path.dirname(inspect.getfile(cls))

    if not path:
        path = os.getcwd()

    return os.path.realpath(path)
869792
def _get_from_path(import_path):
    # type: (str) -> Callable
    
    module_name, obj_name = import_path.rsplit('.', 1)
    module = import_module(module_name)
    return getattr(module, obj_name)
1347918
def find(self, package, **kwargs):
        
        if not exists(package):
            return None
        name, path = None, None
        enforce_init = kwargs.pop('enforce_init', True)
        if isdir(package):
            if isfile(join(package, '__init__.py')) or not enforce_init:
                name, path = basename(package), package
        elif isfile(package) and package.endswith('.py'):
            name, path = splitext(basename(package))[0], package
        if name and path:
            return PackageSpec(name, path)
        return None
906608
def get_class_that_defined_method(meth):
    
    if is_classmethod(meth):
        return meth.__self__
    if hasattr(meth, 'im_class'):
        return meth.im_class
    elif hasattr(meth, '__qualname__'):
        # Python 3
        try:
            cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')
            cls = inspect.getmodule(meth)
            for cls_name in cls_names:
                cls = getattr(cls, cls_name)
            if isinstance(cls, type):
                return cls
        except AttributeError:
            # If this was called from a decorator and meth is not a method, this
            # can result in AttributeError, because at decorator-time meth has not
            # yet been added to module. If it's really a method, its class would be
            # already in, so no problem in that case.
            pass
    raise ValueError(str(meth)+' is not a method.')
718131
def import_cls(cls_name):
    
    path_components = cls_name.split('.')
    module = __import__('.'.join(path_components[:-1]),
                        locals(),
                        globals(),
                        fromlist=path_components[-1:])
    return getattr(module, path_components[-1])
1004538
def load_class(full_class_string):
    
    class_parts = full_class_string.split(".")
    module_path = ".".join(class_parts[:-1])
    class_name = class_parts[-1]

    module = importlib.import_module(module_path)

    return getattr(module, class_name)
476486
def import_by_path(dotted_path, error_prefix=''):
    
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        raise ImproperlyConfigured("%s%s doesn't look like a module path" % (
            error_prefix, dotted_path))
    try:
        module = import_module(module_path)
    except ImportError as e:
        raise ImproperlyConfigured('%sError importing module %s: "%s"' % (
            error_prefix, module_path, e))
    try:
        attr = getattr(module, class_name)
    except AttributeError:
        raise ImproperlyConfigured(
            '%sModule "%s" does not define a "%s" attribute/class' % (
                error_prefix, module_path, class_name
            )
        )
    return attr
823264
def find_spec(self, fullname, path, target=None):
        
        if fullname.startswith(self.package_prefix):
            for path in self._get_paths(fullname):
                if os.path.exists(path):
                    return ModuleSpec(
                        name=fullname,
                        loader=self.loader_class(fullname, path),
                        origin=path,
                        is_package=(path.endswith('__init__.ipynb') or path.endswith('__init__.py')),
                    )
1242729
def get_import_for_type(t):
    """"""
    t_as_string = to_str(t)
    if not is_identifier(t_as_string):
        # this class expanded into something other than a single identifier
        # we can ignore it.  This is the case when we encounter something
        # like the configman.converter.str_to_classes_in_namespaces
        # InnerClassList.  We can safely ignore these things here.
        return (None, None)
    if '.' in t_as_string:
        parts = t_as_string.split('.')
        return ('.'.join(parts[:-1]), parts[-1])
    else:
        if t_as_string in known_mapping_str_to_type:
            return (None, None)
        return (None, t_as_string)
977345
def load_path(self, path):
        '''
        
        '''
        containing_module, _, last_item = path.rpartition('.')
        if last_item[0].isupper():
            # Is a class definition, should do an "import from"
            path = containing_module
        imported_obj = importlib.import_module(path)
        if last_item[0].isupper():
            try:
                imported_obj = getattr(imported_obj, last_item)
            except AttributeError:
                msg = 'Cannot import "%s". ' \
                    '(Hint: CamelCase is only for classes)' % last_item
                raise ConfigurationError(msg)
        return imported_obj
846277
def find_module(cls, fullname, path=None):
        
        spec = cls.find_spec(fullname, path)
        if spec is None:
            return None
        elif spec.loader is None and spec.submodule_search_locations:
            # Here we need to create a namespace loader to handle namespaces since python2 doesn't...
            return NamespaceLoader2(spec.name, spec.submodule_search_locations)
        else:
            return spec.loader
568353
def _import_class_or_module(self, name):
        
        try:
            path, base = self.py_sig_re.match(name).groups()
        except:
            raise ValueError(
                "Invalid class or module '%s' specified for inheritance diagram" % name)
        fullname = (path or '') + base
        path = (path and path.rstrip('.'))
        if not path:
            path = base
        try:
            module = __import__(path, None, None, [])
            # We must do an import of the fully qualified name.  Otherwise if a
            # subpackage 'a.b' is requested where 'import a' does NOT provide
            # 'a.b' automatically, then 'a.b' will not be found below.  This
            # second call will force the equivalent of 'import a.b' to happen
            # after the top-level import above.
            my_import(fullname)
            
        except ImportError:
            raise ValueError(
                "Could not import class or module '%s' specified for inheritance diagram" % name)

        try:
            todoc = module
            for comp in fullname.split('.')[1:]:
                todoc = getattr(todoc, comp)
        except AttributeError:
            raise ValueError(
                "Could not find class or module '%s' specified for inheritance diagram" % name)

        # If a class, just return it
        if inspect.isclass(todoc):
            return [todoc]
        elif inspect.ismodule(todoc):
            classes = []
            for cls in todoc.__dict__.values():
                if inspect.isclass(cls) and cls.__module__ == todoc.__name__:
                    classes.append(cls)
            return classes
        raise ValueError(
            "'%s' does not resolve to a class or module" % name)
1241945
def import_recursive(path):
    
    results = {}
    obj = importlib.import_module(path)
    results[path] = obj
    path = getattr(obj, '__path__', os.path.dirname(obj.__file__))
    for loader, name, is_pkg in pkgutil.walk_packages(path):
        full_name = obj.__name__ + '.' + name
        results[full_name] = importlib.import_module(full_name)
        if is_pkg:
            results.update(import_recursive(full_name))
    return results