1 # Copyright (c) 2010-2011 testtools developers. See LICENSE for details.
12 def try_import(name, alternative=None, error_callback=None):
13 """Attempt to import ``name``. If it fails, return ``alternative``.
15 When supporting multiple versions of Python or optional dependencies, it
16 is useful to be able to try to import a module.
18 :param name: The name of the object to import, e.g. ``os.path`` or
20 :param alternative: The value to return if no module can be imported.
22 :param error_callback: If non-None, a callable that is passed the ImportError
23 when the module cannot be loaded.
25 module_segments = name.split('.')
27 while module_segments:
28 module_name = '.'.join(module_segments)
30 module = __import__(module_name)
32 last_error = sys.exc_info()[1]
38 if last_error is not None and error_callback is not None:
39 error_callback(last_error)
41 nonexistent = object()
42 for segment in name.split('.')[1:]:
43 module = getattr(module, segment, nonexistent)
44 if module is nonexistent:
45 if last_error is not None and error_callback is not None:
46 error_callback(last_error)
51 _RAISE_EXCEPTION = object()
52 def try_imports(module_names, alternative=_RAISE_EXCEPTION, error_callback=None):
53 """Attempt to import modules.
55 Tries to import the first module in ``module_names``. If it can be
56 imported, we return it. If not, we go on to the second module and try
57 that. The process continues until we run out of modules to try. If none
58 of the modules can be imported, either raise an exception or return the
59 provided ``alternative`` value.
61 :param module_names: A sequence of module names to try to import.
62 :param alternative: The value to return if no module can be imported.
63 If unspecified, we raise an ImportError.
64 :param error_callback: If None, called with the ImportError for *each*
65 module that fails to load.
66 :raises ImportError: If none of the modules can be imported and no
67 alternative value was specified.
69 module_names = list(module_names)
70 for module_name in module_names:
71 module = try_import(module_name, error_callback=error_callback)
74 if alternative is _RAISE_EXCEPTION:
76 "Could not import any of: %s" % ', '.join(module_names))
80 def safe_hasattr(obj, attr, _marker=object()):
81 """Does 'obj' have an attribute 'attr'?
83 Use this rather than built-in hasattr, as the built-in swallows exceptions
84 in some versions of Python and behaves unpredictably with respect to
87 return getattr(obj, attr, _marker) is not _marker