~tnurlygayanov/murano/reliase-0.1a

« back to all changes in this revision

Viewing changes to murano-api/muranoapi/openstack/common/importutils.py

  • Committer: Timur Nurlygayanov
  • Date: 2013-05-30 22:18:42 UTC
  • Revision ID: tnulrygayanov@mirantis.com-20130530221842-8e7xd8e89e99n3xz
murano-0.1a

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
 
2
 
 
3
# Copyright 2011 OpenStack LLC.
 
4
# All Rights Reserved.
 
5
#
 
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
 
9
#
 
10
#         http://www.apache.org/licenses/LICENSE-2.0
 
11
#
 
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
 
16
#    under the License.
 
17
 
 
18
"""
 
19
Import related utilities and helper functions.
 
20
"""
 
21
 
 
22
import sys
 
23
import traceback
 
24
 
 
25
 
 
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('.')
 
29
    try:
 
30
        __import__(mod_str)
 
31
        return getattr(sys.modules[mod_str], class_str)
 
32
    except (ValueError, AttributeError):
 
33
        raise ImportError('Class %s cannot be found (%s)' %
 
34
                          (class_str,
 
35
                           traceback.format_exception(*sys.exc_info())))
 
36
 
 
37
 
 
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)
 
41
 
 
42
 
 
43
def import_object_ns(name_space, import_str, *args, **kwargs):
 
44
    """
 
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.
 
48
    """
 
49
    import_value = "%s.%s" % (name_space, import_str)
 
50
    try:
 
51
        return import_class(import_value)(*args, **kwargs)
 
52
    except ImportError:
 
53
        return import_class(import_str)(*args, **kwargs)
 
54
 
 
55
 
 
56
def import_module(import_str):
 
57
    """Import a module."""
 
58
    __import__(import_str)
 
59
    return sys.modules[import_str]
 
60
 
 
61
 
 
62
def try_import(import_str, default=None):
 
63
    """Try to import a module and if it fails return default."""
 
64
    try:
 
65
        return import_module(import_str)
 
66
    except ImportError:
 
67
        return default