【发布时间】:2011-03-08 01:22:23
【问题描述】:
假设我有一个仅用于预生产代码的文件
我想确保它不会在生产代码中运行 - 任何对它的调用都必须失败。
文件顶部的这个 sn-p 不起作用 - 它破坏了 Python 语法,该语法规定 return 必须出现在函数中。
if not __debug__:
return None
这里最好的解决方案是什么 - 就是不涉及制造巨大的其他解决方案。 :-)
【问题讨论】:
标签: python
假设我有一个仅用于预生产代码的文件
我想确保它不会在生产代码中运行 - 任何对它的调用都必须失败。
文件顶部的这个 sn-p 不起作用 - 它破坏了 Python 语法,该语法规定 return 必须出现在函数中。
if not __debug__:
return None
这里最好的解决方案是什么 - 就是不涉及制造巨大的其他解决方案。 :-)
【问题讨论】:
标签: python
if not __debug__:
raise RuntimeError('This module must not be run in production code.')
【讨论】:
if。我可能会使用if __debug__:,把你想要的一切都放在那里,然后你就不需要else。我知道你想避免这种事情,但是:)
也许将非生产代码拆分成一个有条件地从主代码导入的模块?
if __debug__:
import non_production
non_production.main()
更新:根据您的评论,您可能希望查看第 3 方库 pypreprocessor,它允许您在 Python 中执行 C 样式的预处理器指令。他们提供了a debugging example,这似乎与您要查找的内容非常接近(忽略内联调试代码而不需要缩进)。
从该网址复制/粘贴:
from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define debug
#ifdef debug
print('The source is in debug mode')
#else
print('The source is not in debug mode')
#endif
【讨论】:
#ifdef 的内容创建两个不同的文件。
import sys
if not __debug__:
sys.exit()
sys.exit 的文档。
【讨论】:
您可以这样做的一种方法是将该模块中的所有内容隐藏在另一个有条件导入的模块中。
. ├── main.py ├── _test.py ├── test.pymain.py:
import test
print dir(test)
test.py:
if __debug__:
from _test import *
_test.py:
a = 1
b = 2
编辑:
刚刚意识到您在另一个答案中的评论,您说“我希望避免为相当于 #ifdef 的内容创建两个不同的文件”。如another answer 所示,如果没有 if 语句,真的没有任何方法可以做你想做的事。
我已通过 samplebias 对答案进行投票,因为我认为该答案(加上编辑)描述了您在不使用 if 语句的情况下将获得的最接近的答案。
【讨论】: