Python: prevent mixed tabs/spaces on module import

后端 未结 1 1827
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 03:34

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 behaviou

相关标签:
1条回答
  • 2021-01-23 04:17

    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.

    0 讨论(0)
提交回复
热议问题