If settings_module is a filename path import it.
506298
def import_from_filename(obj, filename, silent=False):  # pragma: no cover
    """"""
    if filename in [item.filename for item in inspect.stack()]:
        raise ImportError(
            "Looks like you are loading dynaconf "
            "from inside the {} file and then it is trying "
            "to load itself entering in a circular reference "
            "problem. To solve it you have to "
            "invoke your program from another root folder "
            "or rename your program file.".format(filename)
        )

    _find_file = getattr(obj, "find_file", find_file)
    if not filename.endswith(".py"):
        filename = "{0}.py".format(filename)

    if filename in default_settings.SETTINGS_FILE_FOR_DYNACONF:
        silent = True
    mod = types.ModuleType(filename.rstrip(".py"))
    mod.__file__ = filename
    mod._is_error = False
    try:
        with io.open(
            _find_file(filename),
            encoding=default_settings.ENCODING_FOR_DYNACONF,
        ) as config_file:
            exec(compile(config_file.read(), filename, "exec"), mod.__dict__)
    except IOError as e:
        e.strerror = ("py_loader: error loading file (%s %s)\n") % (
            e.strerror,
            filename,
        )
        if silent and e.errno in (errno.ENOENT, errno.EISDIR):
            return
        raw_logger().debug(e.strerror)
        mod._is_error = True
    return mod
1335484
def ispymodule(self):
        ''''''
        if self.isdir():
            return os.path.isfile(os.path.join(self, '__init__.py'))
        elif self.isfile():
            return self.endswith('.py')
904077
def _import_module_from_path(module_name, plugin_path):
    
    module = None
    try:
        if PY2:
            info = imp.find_module(module_name, [plugin_path])
            if info:
                module = imp.load_module(module_name, *info)
        else:  # Python 3.4+
            spec = importlib.machinery.PathFinder.find_spec(
                module_name,
                [plugin_path])
            if spec:
                module = spec.loader.load_module(module_name)
    except Exception:
        pass

    return module
870291
def _initialize(self, settings_module):
        
        #Get the global settings values and assign them as self attributes
        self.settings_list = []
        for setting in dir(global_settings):
            #Only get upper case settings
            if setting == setting.upper():
                setattr(self, setting, getattr(global_settings, setting))
                self.settings_list.append(setting)

        #If a settings module was passed in, import it, and grab settings from it
        #Overwrite global settings with theses
        if settings_module is not None:
            self.SETTINGS_MODULE = settings_module

            #Try to import the settings module
            try:
                mod = import_module(self.SETTINGS_MODULE)
            except ImportError:
                error_message = "Could not import settings at {0}".format(self.SETTINGS_MODULE)
                log.exception(error_message)
                raise ImportError(error_message)

            #Grab uppercased settings as set them as self attrs
            for setting in dir(mod):
                if setting == setting.upper():
                    if setting == "INSTALLED_APPS":
                        self.INSTALLED_APPS += getattr(mod, setting)
                    else:
                        setattr(self, setting, getattr(mod, setting))
                    self.settings_list.append(setting)

        #If PATH_SETTINGS is in the settings file, extend the system path to include it
        if hasattr(self, "PATH_SETTINGS"):
            for path in self.PATH_SETTINGS:
                sys.path.extend(getattr(self,path))

        self.settings_list = list(set(self.settings_list))
199774
def get_class_from_settings_full_path(settings_key):
    
    cls_path = getattr(settings, settings_key, None)

    if not cls_path:
        raise NotImplementedError()

    try:
        module_name, class_name = cls_path.rsplit('.', 1)
    except ValueError:
        raise ImproperlyConfigured("{0} must be of the form "
                                   "'some.path.module.MyClass'".format(
                                                                settings_key))

    manager_module = importlib.import_module(module_name)

    if not manager_module:
        raise ImproperlyConfigured("{0} refers to a module that has not been "
                                   "installed".format(settings_key))

    return getattr(manager_module, class_name)
735588
def get_app_settings(parser, known_args):
    
    args, dummy_remaining = parser.parse_known_args(known_args)
    settings_module_path = (
        args.settings or os.environ.get('SHELTER_SETTINGS_MODULE', ''))
    if not settings_module_path:
        return None
    return importlib.import_module(settings_module_path)
638930
def load(obj, settings_module, identifier="py", silent=False, key=None):
    """"""
    mod, loaded_from = get_module(obj, settings_module, silent)

    if mod and loaded_from:
        obj.logger.debug("py_loader: {}".format(mod))
    else:
        obj.logger.debug(
            "py_loader: %s (Ignoring, Not Found)", settings_module
        )
        return

    for setting in dir(mod):
        if setting.isupper():
            if key is None or key == setting:
                setting_value = getattr(mod, setting)
                obj.logger.debug(
                    "py_loader: loading %s: %s (%s)",
                    setting,
                    "*****" if "secret" in settings_module else setting_value,
                    identifier,
                )
                obj.set(setting, setting_value, loader_identifier=identifier)

    obj._loaded_files.append(mod.__file__)
53688
def _load_module(self, module_path):
        """"""
        # __import__ will fail on unicode,
        # so we ensure module path is a string here.
        module_path = str(module_path)

        try:
            module_name, attr_name = module_path.split(':', 1)
        except ValueError:  # noqa
            raise self.error(
                '"{}" is not of format "module:parser"'.format(module_path))

        try:
            mod = __import__(module_name, globals(), locals(), [attr_name])
        except (Exception, SystemExit) as exc:  # noqa
            err_msg = 'Failed to import "{}" from "{}". '.format(
                attr_name, module_name)
            if isinstance(exc, SystemExit):
                err_msg += 'The module appeared to call sys.exit()'
            else:
                err_msg += 'The following exception was raised:\n{}'.format(
                    traceback.format_exc())

            raise self.error(err_msg)

        if not hasattr(mod, attr_name):
            raise self.error('Module "{}" has no attribute "{}"'.format(
                module_name, attr_name))

        parser = getattr(mod, attr_name)

        if not isinstance(parser, click.BaseCommand):
            raise self.error('"{}" of type "{}" is not derived from '
                             '"click.BaseCommand"'.format(
                                 type(parser), module_path))
        return parser
46289
def _load_module(module_name, path):
    ''''''
    # TODO: handle the case that the module is already loaded
    try:
        # First try to find a non-builtin, non-frozen, non-special
        # module using the client's search path
        fd, filename, info = imp.find_module(module_name, path)
    except ImportError:
        # The above will fail for builtin, frozen, or special
        # modules. We search for those now...
        fd, filename, info = imp.find_module(module_name)

    # Now import the module given the info found above
    try:
        return imp.load_module(module_name, fd, filename, info)
    finally:
        if fd is not None:
            fd.close()
1323834
def get(name, import_str=False):
    
    value = None
    default_value = getattr(default_settings, name)

    try:
        value = getattr(settings, name)
    except AttributeError:
        if name in default_settings.required_attrs:
            raise Exception('You must set ' + name + ' in your settings.')

    if isinstance(default_value, dict) and value:
        default_value.update(value)
        value = default_value
    else:
        if value is None:
            value = default_value
        value = import_from_str(value) if import_str else value

    return value
448228
def ModulePath(module_name):
  
  module = importlib.import_module(module_name)
  path = inspect.getfile(module)
  # TODO: In Python 2 `inspect.getfile` returns a byte string, so
  # we have to decode that in order to be consistent with Python 3.
  if compatibility.PY2:
    path = path.decode("utf-8")

  # In case of modules with want a path to the directory rather than to the
  # `__init__.py` file itself.
  if os.path.basename(path).startswith("__init__."):
    path = os.path.dirname(path)

  # Sometimes __file__ points at a .pyc file, when we really mean the .py.
  if path.endswith(".pyc"):
    path = path[:-4] + ".py"

  return path
705817
def import_attr(path):
    
    module_path, attr_name = path.rsplit(".", 1)
    return getattr(import_module(module_path), attr_name)
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
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
1107649
def import_from(module, name):
    '''
    
    '''
    module = importlib.import_module(module)
    return getattr(module, name)
60919
def load_module(filename):
  
  basename = os.path.basename(filename)
  path = os.path.dirname(filename)
  sys.path.append(path)
  # TODO(tlan) need to figure out how to handle errors thrown here
  return __import__(os.path.splitext(basename)[0])
200
def find_module(modpath):
    """"""
    module_path = modpath.replace('.', '/') + '.py'
    init_path = modpath.replace('.', '/') + '/__init__.py'
    for root_path in sys.path:
        path = os.path.join(root_path, module_path)
        if os.path.isfile(path):
            return path
        path = os.path.join(root_path, init_path)
        if os.path.isfile(path):
            return path