How do I import custom modules into a hook?

My before_app_launch.py hook was getting a bit large so I was wanting to put some of my code into a separate py file and import it but I cant seem to import a module that is in the same folder as the hook.

hook_folder

Here is my structure. I just want to import software_plugins into my before_app_launch but a simple ‘import software_plugins’ yields a ‘ImportError: No module named software_plugins’ exception.

3 Likes

Hey Anthony!

If the code in your module is something that you might want to use across different hooks in your config, you might want to consider putting it into a Toolkit framework. if you choose to go that route, you can learn how to use the Hook class’s load_framework() method in this post:

If you’d rather just use Python’s import, you’ll need to use sys.path.append() to append the current folder to your Python path, so that the import command knows to look there. You can see an example of sys.path.append() in action here

2 Likes

Due to the way we import the hooks, the folder is not added to the sys.path, so you could add the following to your hook file and then you would be able to import it.

sys.path.append(os.path.dirname(__file__))
import software_plugins

Though a framework might be a good way to go as well.

1 Like