2

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],(How to import a Python class that is in a directory above?) 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.

miguelmorin
  • 5,025
  • 4
  • 29
  • 64
  • @napuzba I read the tutorial. 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, and I updated the question. – miguelmorin Mar 10 '20 at 10:10

0 Answers0