Python:防止模块导入时混合使用制表符/空格 [英] Python: prevent mixed tabs/spaces on module import
问题描述
我知道您可以通过使用-tt
调用Python来确保纯制表符/空格代码.但是,当我无法控制顶级调用时,是否仍可以在脚本加载的模块上强制执行此行为?
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?
推荐答案
如果您可以控制初始脚本,则可以自己添加一个检查.例如,不仅可以导入学生的脚本,还可以使用一个函数,该函数首先检查模块是否存在缩进错误,然后然后导入它:
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()
verifyAndImport
看起来像这样:
import importlib
def verifyAndImport (moduleName):
with open(moduleName + '.py') as f:
# TODO: logic to verify consistent indentation
return importlib.import_module(moduleName)
另一种解决方案是让您的初始脚本在新的Python进程中使用-tt
参数启动 actual 脚本.但是,正如tdelaney指出的那样,这可能会导致不是您的学生造成的错误.
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.
这篇关于Python:防止模块导入时混合使用制表符/空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!