Python: prevent mixed tabs/spaces on module import

2019-02-26 08:53发布

问题:

I know you can ensure pure tabbed/spaced code by calling Python with -tt. However, when I have no control over the top-level call, can I still enforce this behaviour on the modules that are loaded by my script?

回答1:

If you have control about the initial script, then you can just add a check for it yourself. For example, instead of just importing your student’s script, you could have a function that first checks the module for indentation errors, and then imports it:

# instead of
import foo
foo.bar()

# you have something like
foo = verifyAndImport('foo')
foo.bar()

And the verifyAndImport would look like this:

import importlib
def verifyAndImport (moduleName):
    with open(moduleName + '.py') as f:
        # TODO: logic to verify consistent indentation

    return importlib.import_module(moduleName)

An alternative solution would be to have your initial script launch the actual script in a new Python process, with the -tt argument. But as tdelaney pointed out, this may cause errors that are not caused by your students.