10 examples of 'try except python import' in Python

Every line of 'try except python import' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
73def try_import_module(module_name):
74 """
75 Imports a module, but catches import errors. Only catches errors
76 when that module doesn't exist; if that module itself has an
77 import error it will still get raised. Returns None if the module
78 doesn't exist.
79 """
80 try:
81 return import_module(module_name)
82 except ImportError as e:
83 if not getattr(e, 'args', None):
84 raise
85 desc = e.args[0]
86 if not desc.startswith('No module named '):
87 raise
88 desc = desc[len('No module named '):]
89 # If you import foo.bar.baz, the bad import could be any
90 # of foo.bar.baz, bar.baz, or baz; we'll test them all:
91 parts = module_name.split('.')
92 for i in range(len(parts)):
93 if desc == '.'.join(parts[i:]):
94 return None
95 raise
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

22def try_import(package, message=None):
23 """Try import specified package, with custom message support.
24
25 Parameters
26 ----------
27 package : str
28 The name of the targeting package.
29 message : str, default is None
30 If not None, this function will raise customized error message when import error is found.
31
32
33 Returns
34 -------
35 module if found, raise ImportError otherwise
36
37 """
38 try:
39 return __import__(package)
40 except ImportError as e:
41 if not message:
42 raise e
43 raise ImportError(message)
8def try_import_ipython():
9 try:
10 return import_module('IPython')
11 except ImportError:
12 return None
27def _try_import(module_name):
28 """Try importing a module, with an informative error message on failure."""
29 try:
30 mod = importlib.import_module(module_name)
31 return mod
32 except ImportError:
33 err_msg = ("Tried importing %s but failed. See setup.py extras_require. "
34 "The dataset you are trying to use may have additional "
35 "dependencies.")
36 utils.reraise(suffix=err_msg)
306def try_import(mod, config):
307 mod_name = "PySAM." + mod
308 try:
309 i = importlib.import_module(mod_name)
310 m = i.default(config)
311 return m
312 except:
313 print("import error", mod, config)
314 assert False
25def _safe_import(module_name):
26 try:
27 return __import__(module_name,
28 fromlist=[''])
29 except ImportError:
30 # this is ok, there just wasn't a module with custom reports
31 return None
54def try_import(name): # pylint: disable=invalid-name
55 module = None
56 try:
57 module = importlib.import_module(name)
58 except ImportError as e:
59 tf1.logging.warning("Could not import %s: %s" % (name, str(e)))
60 return module
19def _importfrom(modname):
20 # from .edenscmnative import <modname> (where . is looked through this module)
21 fakelocals = {}
22 pkg = __import__("edenscmnative", globals(), fakelocals, [modname], level=0)
23 try:
24 fakelocals[modname] = mod = getattr(pkg, modname)
25 except AttributeError:
26 raise ImportError(r"cannot import name %s" % modname)
27 # force import; fakelocals[modname] may be replaced with the real module
28 getattr(mod, r"__doc__", None)
29 return fakelocals[modname]
90def __import__(name, globals=None, locals=None, fromlist=None):
91 """An alternative to the import function so that we can import
92 modules defined as strings.
93
94 This code was taken from: http://docs.python.org/lib/examples-imp.html
95 """
96 # Fast path: see if the module has already been imported.
97 try:
98 return sys.modules[name]
99 except KeyError:
100 pass
101
102 # If any of the following calls raises an exception,
103 # there's a problem we can't handle -- let the caller handle it.
104 module_name = name.split('.')[-1]
105 module_path = os.path.join(EXAMPLE_DIR, *name.split('.')[:-1])
106
107 fp, pathname, description = imp.find_module(module_name, [module_path])
108
109 try:
110 return imp.load_module(module_name, fp, pathname, description)
111 finally:
112 # Since we may exit via an exception, close fp explicitly.
113 if fp:
114 fp.close()
69def import_module(module_name):
70 '''
71 Imports the specified module by name.
72 '''
73
74 parts = module_name.split('.')
75 module = __import__(module_name)
76 for part in parts[1:]:
77 module = getattr(module, part)
78 return module

Related snippets