1

I am getting an error when I load the module in Python 3.6.

   spec = importlib.util.spec_from_file_location(load_module,path)
   mod = importlib.util.module_from_spec(spec)
   spec.loader.exec_module(mod)

I get the below error:

mod = importlib.util.module_from_spec(spec) File "<frozen importlib._bootstrap>",
line 568, in module_from_spec AttributeError: 'NoneType' object has no attribute 'loader'

How do I do it in the right way?

In the past, I have been using:

mod = importlib.import_module(load_module)

with the path of modules in the path. This works for python 3.7

khelwood
  • 55,782
  • 14
  • 81
  • 108
Abhi
  • 29
  • 2
  • 8

1 Answers1

2

so you can import a module programatically like so:

my_module = importlib.import_module('my_module')

To specify a custom path you can use:

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

If you're getting the error below, it means that spec_from_file_location couldn't locate the module and path you specified and returned None.

in module_from_spec AttributeError: 'NoneType' object has no attribute 'loader'
jspcal
  • 50,847
  • 7
  • 72
  • 76
  • Using `importlib.machinery` is an alternative which worked for me pretty well: https://stackoverflow.com/a/19011259/5308983 – thinwybk May 11 '20 at 13:50