Lazily import the numpy module
965707
def numpy():
        ''''''
        if LazyImport.numpy_module is None:
            try:
                LazyImport.numpy_module = __import__('numpypy')
            except ImportError:
                try:
                    LazyImport.numpy_module = __import__('numpy')
                except ImportError:
                    raise ImportError('The numpy module is required')
        return LazyImport.numpy_module
499452
def _load(module, globals_dict=None, symb_list=None):
    
    if globals_dict is None:
        globals_dict = six.moves.builtins.__dict__
    try:
        mod = importlib.import_module(module)
        if '__all__' in mod.__dict__:
            # import listed symbols
            for name in mod.__dict__['__all__']:
                if symb_list is not None:
                    symb_list.append(name)
                globals_dict[name] = mod.__dict__[name]
        else:
            # only import non-private symbols
            for name, sym in six.iteritems(mod.__dict__):
                if _validate_local(name):
                    if symb_list is not None:
                        symb_list.append(name)
                    globals_dict[name] = sym
    except Exception:
        log_interactive.error("Loading module %s", module, exc_info=True)
376353
def call(fun, **kwargs):
    '''
    
    '''
    args = kwargs.get('args', [])
    dirs = kwargs.get('dirs', [])

    funcs = LazyLoader(
        [os.path.join(SALT_BASE_PATH, 'modules')] + dirs,
        None,
        tag='modules',
        virtual_enable=False,
    )
    return funcs[fun](*args)
271875
def pseudo_import(fname):
  
  is_d_import = lambda n: isinstance(n, ast.Name) and n.id == "__import__"
  is_assign = lambda n: isinstance(n, ast.Assign)
  is_valid = lambda n: is_assign(n) and not any(map(is_d_import, ast.walk(n)))
  with open(fname, "r") as f:
    astree = ast.parse(f.read(), filename=fname)
  astree.body = [node for node in astree.body if is_valid(node)]
  return locals_from_exec(compile(astree, fname, mode="exec"))
1088347
def _load_module(module):
    
    modclass = type(module)
    # We only take care of our own LazyModule instances
    if not issubclass(modclass, LazyModule):
        raise TypeError("Passed module is not a LazyModule instance.")
    with _ImportLockContext():
        parent, _, modname = module.__name__.rpartition('.')
        logger.debug("loading module {}".format(modname))
        # We first identify whether this is a loadable LazyModule, then we
        # strip as much of lazy_import behavior as possible (keeping it cached,
        # in case loading fails and we need to reset the lazy state).
        if not hasattr(modclass, '_lazy_import_error_msgs'):
            # Alreay loaded (no _lazy_import_error_msgs attr). Not reloading.
            return
        # First, ensure the parent is loaded (using recursion; *very* unlikely
        # we'll ever hit a stack limit in this case).
        modclass._LOADING = True
        try:
            if parent:
                logger.debug("first loading parent module {}".format(parent))
                setattr(sys.modules[parent], modname, module)
            if not hasattr(modclass, '_LOADING'):
                logger.debug("Module {} already loaded by the parent"
                             .format(modname))
                # We've been loaded by the parent. Let's bail.
                return
            cached_data = _clean_lazymodule(module)
            try:
                # Get Python to do the real import!
                reload_module(module)           
            except:
                # Loading failed. We reset our lazy state.
                logger.debug("Failed to load module {}. Resetting..."
                             .format(modname))
                _reset_lazymodule(module, cached_data)
                raise
            else:
                # Successful load
                logger.debug("Successfully loaded module {}".format(modname))
                delattr(modclass, '_LOADING')
                _reset_lazy_submod_refs(module)

        except (AttributeError, ImportError) as err:
            logger.debug("Failed to load {}.\n{}: {}"
                         .format(modname, err.__class__.__name__, err))
            logger.lazy_trace()
            # Under Python 3 reloading our dummy LazyModule instances causes an
            # AttributeError if the module can't be found. Would be preferrable
            # if we could always rely on an ImportError. As it is we vet the
            # AttributeError as thoroughly as possible.
            if ((six.PY3 and isinstance(err, AttributeError)) and not
                err.args[0] == "'NoneType' object has no attribute 'name'"):
                # Not the AttributeError we were looking for.
                raise
            msg = modclass._lazy_import_error_msgs['msg']
            raise_from(ImportError(
                msg.format(**modclass._lazy_import_error_strings)), None)
1328085
def import_obj(clsname, default_module=None):
    
    if default_module is not None:
        if not clsname.startswith(default_module + '.'):
            clsname = '{0}.{1}'.format(default_module, clsname)
    mod, clsname = clsname.rsplit('.', 1)
    mod = importlib.import_module(mod)
    try:
        obj = getattr(mod, clsname)
    except AttributeError:
        raise ImportError('Cannot import {0} from {1}'.format(clsname, mod))
    return obj
1181853
def import_module(module_name):
    """"""
    import sys, os
    import importlib
    sys.path.append(os.path.dirname(__file__))
    return importlib.import_module(module_name)
388720
def _do_magic_import(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
        
        if callable(STATIC_ROOT):
            files = sorted(STATIC_ROOT(name))
        else:
            glob_path = os.path.join(STATIC_ROOT, name)
            files = glob.glob(glob_path)
            files = sorted((file[len(STATIC_ROOT):], None) for file in files)

        if files:
            # Build magic context
            map_name = os.path.normpath(
                os.path.dirname(name)).replace('\\', '_').replace('/', '_')
            kwargs = {}

            def setdefault(var, val):
                _var = '$' + map_name + '-' + var
                if _var in rule[CONTEXT]:
                    kwargs[var] = interpolate(rule[CONTEXT][_var], rule)
                else:
                    rule[CONTEXT][_var] = val
                    kwargs[var] = interpolate(val, rule)
                return rule[CONTEXT][_var]

            setdefault(
                'sprite-base-class', StringValue('.' + map_name + '-sprite'))
            setdefault('sprite-dimensions', BooleanValue(False))
            position = setdefault('position', NumberValue(0, '%'))
            spacing = setdefault('spacing', NumberValue(0))
            repeat = setdefault('repeat', StringValue('no-repeat'))
            names = tuple(os.path.splitext(
                os.path.basename(file))[0] for file, storage in files)
            for n in names:
                setdefault(n + '-position', position)
                setdefault(n + '-spacing', spacing)
                setdefault(n + '-repeat', repeat)
            sprite_map = _sprite_map(name, **kwargs)
            rule[CONTEXT]['$' + map_name + '-' + 'sprites'] = sprite_map
            ret = '''
                @import "compass/utilities/sprites/base";

                // All sprites should extend this class
                // The %(map_name)s-sprite mixin will do so for you.
                #{$%(map_name)s-sprite-base-class} {
                    background: $%(map_name)s-sprites;
                }

                // Use this to set the dimensions of an element
                // based on the size of the original image.
                @mixin %(map_name)s-sprite-dimensions($name) {
                    @include sprite-dimensions($%(map_name)s-sprites, $name);
                }

                // Move the background position to display the sprite.
                @mixin %(map_name)s-sprite-position($name, $offset-x: 0, $offset-y: 0) {
                    @include sprite-position($%(map_name)s-sprites, $name, $offset-x, $offset-y);
                }

                // Extends the sprite base class and set the background position for the desired sprite.
                // It will also apply the image dimensions if $dimensions is true.
                @mixin %(map_name)s-sprite($name, $dimensions: $%(map_name)s-sprite-dimensions, $offset-x: 0, $offset-y: 0) {
                    @extend #{$%(map_name)s-sprite-base-class};
                    @include sprite($%(map_name)s-sprites, $name, $dimensions, $offset-x, $offset-y);
                }

                @mixin %(map_name)s-sprites($sprite-names, $dimensions: $%(map_name)s-sprite-dimensions) {
                    @include sprites($%(map_name)s-sprites, $sprite-names, $%(map_name)s-sprite-base-class, $dimensions);
                }

                // Generates a class for each sprited image.
                @mixin all-%(map_name)s-sprites($dimensions: $%(map_name)s-sprite-dimensions) {
                    @include %(map_name)s-sprites(%(sprites)s, $dimensions);
                }
            ''' % {'map_name': map_name, 'sprites': ' '.join(names)}
            return ret
786645
def visit_Import(self, node):
        
        for alias in node.names:
            current_module = MODULES
            # Recursive check for submodules
            for path in alias.name.split('.'):
                if path not in current_module:
                    raise PythranSyntaxError(
                        "Module '{0}' unknown.".format(alias.name),
                        node)
                else:
                    current_module = current_module[path]
1201558
def _import_module(self, s):
        
        mod = __import__(s)
        parts = s.split('.')
        for part in parts[1:]:
            mod = getattr(mod, part)
        return mod
834351
def visit_Module(self, node):
        """"""
        self.generic_visit(node)
        import_alias = ast.alias(name='itertools', asname=mangle('itertools'))
        if self.use_itertools:
            importIt = ast.Import(names=[import_alias])
            node.body.insert(0, importIt)
        return node
990757
def load(self, modules):
        
        self.modules_assoc = []
        for module in modules:
            if not module.enabled:
                logger.info("Module %s is declared but not enabled", module.name)
                # Store in our modules list but do not try to load
                # Probably someone else will load this module later...
                self.modules[module.uuid] = module
                continue
            logger.info("Importing Python module '%s' for %s...", module.python_name, module.name)
            try:
                python_module = importlib.import_module(module.python_name)

                # Check existing module properties
                # Todo: check all mandatory properties
                if not hasattr(python_module, 'properties'):  # pragma: no cover
                    self.configuration_errors.append("Module %s is missing a 'properties' "
                                                     "dictionary" % module.python_name)
                    raise AttributeError
                logger.info("Module properties: %s", getattr(python_module, 'properties'))

                # Check existing module get_instance method
                if not hasattr(python_module, 'get_instance') or \
                        not isinstance(getattr(python_module, 'get_instance'),
                                       collections.Callable):  # pragma: no cover
                    self.configuration_errors.append("Module %s is missing a 'get_instance' "
                                                     "function" % module.python_name)
                    raise AttributeError

                self.modules_assoc.append((module, python_module))
                logger.info("Imported '%s' for %s", module.python_name, module.name)
            except ImportError as exp:  # pragma: no cover, simple protection
                self.configuration_errors.append("Module %s (%s) can't be loaded, Python "
                                                 "importation error: %s" % (module.python_name,
                                                                            module.name,
                                                                            str(exp)))
            except AttributeError:  # pragma: no cover, simple protection
                self.configuration_errors.append("Module %s (%s) can't be loaded, "
                                                 "module configuration" % (module.python_name,
                                                                           module.name))
            else:
                logger.info("Loaded Python module '%s' (%s)", module.python_name, module.name)
999842
def visit_Import(self, node, frame):
        """"""
        if node.with_context:
            self.unoptimize_scope(frame)
        self.writeline('l_%s = ' % node.target, node)
        if frame.toplevel:
            self.write('context.vars[%r] = ' % node.target)
        self.write('environment.get_template(')
        self.visit(node.template, frame)
        self.write(', %r).' % self.name)
        if node.with_context:
            self.write('make_module(context.parent, True, locals())')
        else:
            self.write('module')
        if frame.toplevel and not node.target.startswith('_'):
            self.writeline('context.exported_vars.discard(%r)' % node.target)
        frame.assigned_names.add(node.target)
433209
def utils(opts, whitelist=None, context=None, proxy=proxy):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
        opts,
        tag='utils',
        whitelist=whitelist,
        pack={'__context__': context, '__proxy__': proxy or {}},
    )
490812
def lazy(decorator):
    """"""
    def decorate(fn, *args, **kwargs):
        name = fn.__name__
        parent = decorator(fn, *args, **kwargs)
        #doc = _add_msg(getattr(parent, '__doc__', None), '*@lazy*')
        doc = getattr(parent, '__doc__', None)
        if hasattr(parent, '__set__') or hasattr(parent, '__delete__'):
            return _lazy_data(name, parent, doc)
        else:
            return _lazy_nondata(name, parent, doc)
    return decorate
1284462
def _import_module(name, package=None):
    
    if name.startswith('.'):
        name = '{package}.{module}'.format(package=package, module=str(name).strip('.'))
    __import__(name)
    return sys.modules[name]
505885
def try_import(module_name, names=None, default=ImportErrorModule, warn=True):
    
    try:
        module = importlib.import_module(module_name)
    except ImportError:
        if warn:
            if warn is True:
                Config.utils_logger.warning(
                    "Module `%s` not found. Install it to remove this warning"
                    % module_name
                )
            else:
                warn(module_name, names, default)
        module = (
            ImportErrorModule(module_name) if default is ImportErrorModule else default
        )
    if not names:
        return module
    if not isinstance(names, (tuple, set, list)):
        names = [names]
    result = []
    for name in names:
        if hasattr(module, name):
            result.append(module.__getattribute__(name))
        else:
            result.append(
                ImportErrorModule("%s.%s" % (module_name, name))
                if default is ImportErrorModule
                else default
            )
    return result[0] if len(result) == 1 else result