views:

253

answers:

2

The Python interpreter can be started with -tt to raise a TabError exception if the interpreted file has inconsistent tab usage.

I'm trying to write a pre-commit hook for SVN that rejects files that raise this exception. I can pass the file being committed to python -tt but my problem is that the file is also executed, besides being checked. Is there a way to tell Python "just analyze the file, don't run it"? Or maybe some other approach would be better for accomplishing what I want.

+4  A: 

You can do this using the py_compile module:

$ python -tt -c "import py_compile; py_compile.compile('test.py', doraise=True)"

The doraise=True will raise an exception and return with a nonzero exit code that you can easily test in your pre-commit hook.

Greg Hewgill
Great solution, thank you!
Catalin Iacob
+1  A: 

The preferred tab usage in Python is no tab usage at all (use four spaces for indentation). If that is your coding style then the problem may be reduced to checking if there are any tabs in the code. And this can be easily done with simple regexp, even with 'grep', so there is no even need to run the interpreter.

The 'py_compile' way have other advantage, though: it also checks Python code syntax, which may be desirable (though costs a bit of computation power of the SVN server).

Jacek Konieczny
I know that spaces are preferred according to PEP8. But still this seems a pragmatic and simple solution which doesn't force us to change lots of files and editor settings to use spaces (only for Python) and still makes sure that the scripts are correct.
Catalin Iacob