我能想到的唯一解决方案是导入钩子。虽然这有点超出了我希望做的事情,但我觉得这是我了解它们如何工作的一个很好的借口。
该解决方案不检查“不一致的空白”,它只检查制表符,但它很容易扩展。
结果如下:
import sys
import imp
import warnings
class TabCheckImporter(object):
"""Finder and loader class for checking for the presence of tabs
"""
def find_module(self, fullname, path=None):
"""Module finding method
"""
# Save the path so we know where to look in load_module
self.path = path
return self
def load_module(self, name):
"""Module loading method.
"""
# Check if it was already imported
module = sys.modules.get(name)
if module is not None:
return module
# Find the module and check for tabs
file_, pathname, description = imp.find_module(name, self.path)
try:
content = file_.read()
tab = content.find("\t")
if tab > -1:
lineno = content[:tab].count("\n") + 1
warnings.warn_explicit(
"module '{0}' contains a tab character".format(name),
ImportWarning,
pathname,
lineno)
except Exception as e:
warnings.warn("Module '{0}' could not be checked".format(name),
ImportWarning)
# Import the module
try:
module = imp.load_module(name, file_, pathname, description)
finally:
if file_:
file_.close()
sys.modules[name] = module
return module
# Register the hook
sys.meta_path = (sys.meta_path or []) + [TabCheckImporter()]
# Enable ImportWarnings
warnings.simplefilter("always", ImportWarning)
导入此文件(替换->|
为文字选项卡):
# File: test_tabbed.py
if True:
->| print "This line starts with a tab"
产生这个输出:
$ python -c 'import hook; import test_normal; import test_tabbed;'
test_tabbed.py:3: ImportWarning: module 'test_tabbed' contains a tab character
print "This line starts with a tab"