1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2011 OpenStack Foundation.
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):
44
"""Tries to import object from default namespace.
46
Imports a class and return an instance of it, first by trying
47
to find the class in a default namespace, then failing back to
48
a full path if not found in the default namespace.
50
import_value = "%s.%s" % (name_space, import_str)
52
return import_class(import_value)(*args, **kwargs)
54
return import_class(import_str)(*args, **kwargs)
57
def import_module(import_str):
58
"""Import a module."""
59
__import__(import_str)
60
return sys.modules[import_str]
63
def try_import(import_str, default=None):
64
"""Try to import a module and if it fails return default."""
66
return import_module(import_str)