Skip to content
This repository has been archived by the owner on Oct 14, 2023. It is now read-only.

How to import a custom python module file into azure function #44

Open
infact opened this issue Sep 18, 2020 · 2 comments
Open

How to import a custom python module file into azure function #44

infact opened this issue Sep 18, 2020 · 2 comments

Comments

@infact
Copy link

infact commented Sep 18, 2020

How to import a custom python module file into azure function.
My python class needs to import my custom class. For instance

import os
import time
from optparse import OptionParser
**from mlutil import HTMLPath**

How can I upload/where to upload my mlutil.py file so that my import from mlutil class won't throw error in my azure function ?

@snobu
Copy link
Collaborator

snobu commented Sep 18, 2020

Have you looked at this section in the docs?
https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python#import-behavior

__app__
| - my_first_function
| | - __init__.py
| | - function.json
| | - example.py
| - my_second_function
| | - __init__.py
| | - function.json
| - shared_code
| | - my_first_helper_function.py
| | - my_second_helper_function.py
| - host.json
| - requirements.txt
| - Dockerfile
tests

You can import modules in your function code using both explicit relative and absolute references. Based on the folder structure shown above, the following imports work from within the function file __app__\my_first_function\__init__.py:

from . import example #(explicit relative)

from ..shared_code import my_first_helper_function #(explicit relative)

from __app__ import shared_code #(absolute)

import __app__.shared_code #(absolute)

@t-souravgoel
Copy link

t-souravgoel commented Jun 12, 2021

Hi, adding to the above solution by @snobu, if you want to use absolute import and have nested directories, you can add your packages / module directories into python system variables using
import sys
sys.path.append('path to package or module with azure function directory as the root directory')
The root directory is the directory containing the function.json file

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants