Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing module in pre-commit hook requires runtime path addition

I want to import and test a module in a pre-commit hook in .git/hooks/pre-commit. The structure is:

set_prefix.py
temp.py
.git
  |----hooks
         |----pre-commit

The file set_prefix.py could simply be:

def main():
    pass

The file temp.py is:

import set_prefix

Calling python3 temp.py throws no error.

For .git/hooks/pre-commit, I confirmed with import os; print(os.getcwd()) that the working directory is the same as set_prefix.py.

The following imports fail:

  • import set_prefix fails with ModuleNotFoundError: No module named 'set_prefix'
  • from . import set_prefix fails with ImportError: attempted relative import with no known parent package (probably because it's not part of a package).

One import that works, from this thread requires adding to the path at runtime:

import sys
sys.path.append(".") # Adds current directory to python modules path.
from . import set_prefix

Why does importing behave differently between a file on the same directory and the pre-commit hook if they both have the same current directory at runtime?

Update

Another solution, mentioned in the comments, is to turn the directory into a package with an __init__.py file. But I still don't understand why the import works from temp.py and not from the pre-commit hook if they both run from the same directory.

like image 349
miguelmorin Avatar asked Mar 28 '26 07:03

miguelmorin


1 Answers

The pre-commit hook creates an env where it only has the changed files (the ones after filtering through the regex of files option) to make the pre-commit check fast.
The set_prefix.py file that you mentioned, needs to have changes for it to be added to the pre-commit env. Therefore the file is not found while running pre-commit hooks but it works when the test is run normally.

One solution would be to also pass the set_prefix.py file to the arguments in the pre-commit hook (If it is pylint or another linter)

like image 155
Scramjet Avatar answered Mar 29 '26 20:03

Scramjet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!