Edgar H
Edgar H

Reputation: 1518

How to use importlib?

I need to move some code to an Azure function but the code needs to continue to work as a service fabric app for the time being. The python code is in a directory with a . in the name "DocClassify.Api", so I cannot just import it normally.

Importlib has a nice example on how to import a module given a file filepath. However, when I try this, I cannot call the functions in the module.

Here a minimal example:

test_file.py

import logging


def function_one():
    print('function one')
    logging.info('function one')

main.py

import sys
import importlib.util

module_name = 'test_file'
spec = importlib.util.spec_from_file_location(module_name, r'C:\Users\developer\Downloads\test_file.py')
tf = importlib.util.module_from_spec(spec)
sys.modules[module_name] = tf

print(tf.__name__)
tf.function_one()

The output this produces is

test_file
Traceback (most recent call last):
  File "C:\Users\edgar.haener\repos\sandbox\main.py", line 11, in <module>
    tf.function_one()
AttributeError: module 'test_file' has no attribute 'function_one'

I'm not sure what I'm doing wrong.

Upvotes: 0

Views: 240

Answers (1)

Edgar H
Edgar H

Reputation: 1518

I found my mistake, I need to call the loader

spec.loader.exec_module(foo)

So the correct way is

import sys
import importlib.util

module_name = 'test_file'
spec = importlib.util.spec_from_file_location(module_name, r'C:\Users\developer\Downloads\test_file.py')
tf = importlib.util.module_from_spec(spec)
spec.loader.exec_module(tf)
sys.modules[module_name] = tf

Upvotes: 1

Related Questions