不允许开发者使用打印方式

躁狂症

我开发了一个正在被其他人使用的 python 框架。为了将任何数据打印到输出,开发人员应该使用 Log 类(Log.print(...)),而不应该直接使用 print() 方法。有什么方法可以在整个代码中强制执行此规则?例如,当开发人员直接使用打印方法时抛出错误,如下所示:

Error: print method cannot be called directly. Please use Log.print().

抑制打印(如这里所讨论的)不是一个好主意,因为开发人员可能会感到困惑。

游戏机

Actullay,下面两行代码是一样的:

sys.stdout.write('hello'+'\n')
print('hello')

因此,您可以将 sys.stdout 重定向到在调用 print 时引发异常的类。

import sys

class BlockPrint():
    call_print_exception = Exception('Error: print method cannot be called directly. Please use Log.print().')
    def write(self, str):
        raise self.call_print_exception

bp = BlockPrint()
sys.stdout=bp

print('aaa')

输出:

Traceback (most recent call last):
  File "p.py", line 12, in <module>
    print('aaa')
  File "p.py", line 7, in write
    raise self.call_print_exception
Exception: Error: print method cannot be called directly. Please use Log.print().

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章