10 examples of 'python import class' in Python

Every line of 'python import class' 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
27def my_import(name):
28 """ dynamic importing """
29 module, attr = name.rsplit('.', 1)
30 mod = __import__(module, fromlist=[attr])
31 klass = getattr(mod, attr)
32 return klass()
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
26def import_object(name):
27 module, member = name.rpartition('.')[::2]
28 module = __import__(module, fromlist=[None])
29 try:
30 return getattr(module, member)
31 except AttributeError:
32 raise ImportError('Module "{}" has no member "{}"'.format(module, member))
72def import_object(import_str):
73 """Returns an object including a module or module and class"""
74 try:
75 __import__(import_str)
76 return sys.modules[import_str]
77 except ImportError:
78 cls = import_class(import_str)
79 return cls()
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()
37def import_class(from_path, full_class_name):
38 from_path = str(from_path)
39 full_class_name = str(full_class_name)
40 try:
41 return import_class_from_path(from_path, full_class_name)
42 except Exception as e:
43 our_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
44 api_dir = os.path.join(our_dir, PULSAR_API_ROOT, PULSAR_FUNCTIONS_API_ROOT)
45 try:
46 return import_class_from_path(api_dir, full_class_name)
47 except Exception as e:
48 Log.info("Failed to import class %s from path %s" % (full_class_name, from_path))
49 Log.info(e, exc_info=True)
50 return None
15def import_class(path):
16 path_bits = path.split('.')
17 # Cut off the class name at the end.
18 class_name = path_bits.pop()
19 module_path = '.'.join(path_bits)
20 module_itself = importlib.import_module(module_path)
21
22 if not hasattr(module_itself, class_name):
23 raise ImportError("The Python module '%s' has no '%s' class." % (module_path, class_name))
24
25 return getattr(module_itself, class_name)
43def import_string(import_name, silent=False):
44 """Imports an object based on a string. This is useful if you want to
45 use import paths as endpoints or something similar. An import path can
46 be specified either in dotted notation (``xml.sax.saxutils.escape``)
47 or with a colon as object delimiter (``xml.sax.saxutils:escape``).
48
49 If `silent` is True the return value will be `None` if the import fails.
50
51 :param import_name: the dotted name for the object to import.
52 :param silent: if set to `True` import errors are ignored and
53 `None` is returned instead.
54 :return: imported object
55 """
56 try:
57 if ':' in import_name:
58 module, obj = import_name.split(':', 1)
59 elif '.' in import_name:
60 module, obj = import_name.rsplit('.', 1)
61 else:
62 return __import__(import_name)
63 return getattr(__import__(module, None, None, [obj]), obj)
64 except (ImportError, AttributeError):
65 if not silent:
66 raise
11def import_module(name):
12 __import__("%s" % (name,), globals(), locals(), [], -1)
13 return sys.modules[name]
141def import_string(module_name, package=None):
142 """
143 import a module or class by string path.
144
145 :module_name: str with path of module or path to import and
146 instanciate a class
147 :returns: a module object or one instance from class if
148 module_name is a valid path to class
149
150 """
151 module, klass = module_name.rsplit(".", 1)
152 module = import_module(module, package=package)
153 obj = getattr(module, klass)
154 if ismodule(obj):
155 return obj
156 return obj()

Related snippets