Question

Does CPython interpreter provide any hooks to grab and inspect .py source files as they are being loaded?

I was thinking if PEP 666 http://www.python.org/dev/peps/pep-0666/ could be implemented with the existing interpreter. One could force additional source code syntax checks like tabs and spaces mix check there.

I am well aware that the best practice is lint your source offline, but I am just playing with the idea to see if it is possible.

Was it helpful?

Solution

Maybe the following helps you get started...

import sys
import os
import random


class GrammarNaziError(SyntaxError):
    pass


class GrammarNaziImporter(object):
    def find_module(self, module_name, package_path):
        if package_path:
            search_paths = package_path
            module_name = module_name.split('.')[-1]

        else:
            search_paths = sys.path + [ '.' ]

        for i in search_paths:
            path = os.path.join(i, module_name)
            if os.path.isdir(path):
                path = os.path.join(path, '__init__.py')
            else:
                path += '.py'

            if os.path.exists(path):
                if not self.valid_syntax(path):
                    raise GrammarNaziError(
                        "The module %s failed Grammar Nazi Inspection" % path)

                break

    def valid_syntax(self, path):
        return random.randint(0, 10) # substitute with logic of your choice

rest = GrammarNaziImporter()
sys.meta_path.insert(0, rest)

P.S. Good luck ;)

P.P.S. Edited so that the code works for init.py's and fails fast for found modules

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top