1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2011 OpenStack LLC.
6
# Licensed under the Apache License, Version 2.0 (the "License"); you may
7
# not use this file except in compliance with the License. You may obtain
8
# a copy of the License at
10
# http://www.apache.org/licenses/LICENSE-2.0
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
# License for the specific language governing permissions and limitations
19
Import related utilities and helper functions.
26
def import_class(import_str):
27
"""Returns a class from a string including module and class"""
28
mod_str, _sep, class_str = import_str.rpartition('.')
31
return getattr(sys.modules[mod_str], class_str)
32
except (ValueError, AttributeError):
33
raise ImportError('Class %s cannot be found (%s)' %
35
traceback.format_exception(*sys.exc_info())))
38
def import_object(import_str, *args, **kwargs):
39
"""Import a class and return an instance of it."""
40
return import_class(import_str)(*args, **kwargs)
43
def import_object_ns(name_space, import_str, *args, **kwargs):
45
Import a class and return an instance of it, first by trying
46
to find the class in a default namespace, then failing back to
47
a full path if not found in the default namespace.
49
import_value = "%s.%s" % (name_space, import_str)
51
return import_class(import_value)(*args, **kwargs)
53
return import_class(import_str)(*args, **kwargs)
56
def import_module(import_str):
57
"""Import a module."""
58
__import__(import_str)
59
return sys.modules[import_str]
62
def try_import(import_str, default=None):
63
"""Try to import a module and if it fails return default."""
65
return import_module(import_str)