Source code for vmware.vapi.lib.load

"""
Convenience methods for dynamic loading
"""

__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2011-2014 VMware, Inc.  All rights reserved. -- VMware Confidential'

import logging
import six

from vmware.vapi.settings import config

logger = logging.getLogger(__name__)


[docs]def dynamic_import(constructor): """ Dynamically import a module and get the specified module attribute :type constructor: :class:`str` :param constructor: Fully qualified module attribute :rtype: :class:`object` :return: Python object """ target_attr = None if constructor: if isinstance(constructor, six.string_types): try: module_name, fn = constructor.rsplit('.', 1) module = __import__(module_name, globals(), locals(), [fn]) target_attr = getattr(module, fn) except ImportError as err: logger.exception('Import failed: %s: module %s fn %s', str(err), module_name, fn) target_attr = None except AttributeError as err: logger.exception('Import failed: Module %s has no %s', module_name, fn) target_attr = None return target_attr
[docs]def import_multiple_classes(section, property_key): """ Import multiple class names provided in the config file :type section: :class:`str` :param section: Name of the section in the config file :type property_key: :class:`str` :param property_key: Name of the property in the config file :rtype: :class:`list` of :class:`str` :return: List of class references """ cfg = config.cfg classes = [] if cfg and cfg.has_section(section) and cfg.has_option(section, property_key): class_names = cfg.get(section, property_key).split(',') for class_name in class_names: class_name = class_name.strip() class_ref = dynamic_import(class_name) if class_ref is not None: classes.append(class_ref()) return classes