Python: prevent mixed tabs/spaces on module import

荒凉一梦 提交于 2019-12-20 02:52: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.



来源:https://stackoverflow.com/questions/28945693/python-prevent-mixed-tabs-spaces-on-module-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!