10 examples of 'how to import a function from another python file' in Python

Every line of 'how to import a function from another python 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
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()
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

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()
36def import_func(func):
37 if isinstance(func, str):
38 assert ":" in func, "{!r} should have format 'module:callable'".format(func)
39 module_name, func_name = func.split(":", 1)
40 module = import_module(module_name)
41 func = getattr(module, func_name)
42 assert callable(func), "{!r} is not callable".format(func)
43 return func
56def _my_import(fullname):
57 # helper function to import dotted modules
58 return __import__(fullname, globals(), locals(), ['DUMMY'])
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)
76def Import(self, name: str, *args: Any, **kwargs: Any) -> "Import":
77 return Import(self._module, name, *args, **kwargs)
2def new_module(module):
3 import sys
4 save = list(sys.path)
5 sys.path.clear()
6 sys.path.append('/tmp')
7 m = None
8 with open('/tmp/%s.py' % module,'w') as empty:
9 empty.write('#\n')
10
11 try:
12 m = __import__(module)
13 except Exception as e :
14 sys.print_exception(e)
15 finally:
16 import sys
17 sys.path.clear()
18 sys.path.extend(save)
19 print("#TODO: os.remove / unlink empty mod")
20 return m
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()
241def import_from_path(path, name="esptool"):
242 if not os.path.isfile(path):
243 raise Exception("No such file: %s" % path)
244
245 # Import esptool from the provided location
246 if sys.version_info >= (3,5):
247 import importlib.util
248 spec = importlib.util.spec_from_file_location(name, path)
249 module = importlib.util.module_from_spec(spec)
250 spec.loader.exec_module(module)
251 elif sys.version_info >= (3,3):
252 from importlib.machinery import SourceFileLoader
253 module = SourceFileLoader(name, path).load_module()
254 else:
255 import imp
256 module = imp.load_source(name, path)
257 return module

Related snippets