10 examples of 'python import class from another file' in Python

Every line of 'python import class from another file' 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
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()
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

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
609def importFrom(modname, objname, asTuple=False):
610 """
611 Import `modname` and return reference to `objname` within the module.
612
613 :param modname: (str) the name of a Python module
614 :param objname: (str) the name of an object in module `modname`
615 :param asTuple: (bool) if True a tuple is returned, otherwise just the object
616 :return: (object or (module, object)) depending on `asTuple`
617 """
618 from importlib import import_module
619
620 module = import_module(modname, package=None)
621 obj = getattr(module, objname)
622 return ((module, obj) if asTuple else obj)
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
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]
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()
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()
65def _import_classes_from_module(module_name, classes):
66 module = new_module(module_name)
67 imported_module = __import__(module_name, fromlist=classes)
68 for classname in classes:
69 module.__setattr__(classname, getattr(imported_module, classname))
70 return module
23def import_modules(source_code: str):
24 results = {}
25 imports = parse_imports(source_code)
26 for import_ in imports:
27 module = import_.module if import_.module else import_.name
28 loaded_module = importlib.import_module(module)
29
30 if not import_.name == module:
31 loaded_module = getattr(loaded_module, import_.name)
32
33 if import_.alias:
34 results[import_.alias] = loaded_module
35 else:
36 results[import_.name] = loaded_module
37
38 return results

Related snippets