你如何实现“#ifdef"?在蟒蛇? [英] How do you implement "#ifdef" in python?
问题描述
C
中的编程 我曾经有一些代码段仅用于调试目的(记录命令等).通过使用 #ifdef
预处理器指令,可以完全禁用这些语句,如下所示:
#ifdef 宏受控文本#endif/* 宏 */
在 python
中执行类似操作的最佳方法是什么?
如果您只想禁用日志记录方法,请使用 logging
模块.如果日志级别设置为排除,比如调试语句,那么 logging.debug
将非常接近无操作(它只检查日志级别并返回而不插入日志字符串).
如果您想在以特定变量为条件的字节码编译时实际删除代码块,您唯一的选择是相当神秘的 __debug__
全局变量.除非将 -O
标志传递给 Python(或将 PYTHONOPTIMIZE
设置为环境中的非空值),否则此变量设置为 True
.
如果在if
语句中使用__debug__
,if
语句实际上只编译成True
分支.这种特殊的优化与 Python 曾经获得的预处理器宏一样接近.
请注意,与宏不同,您的代码在 if
的两个分支中的语法仍然必须正确.
要展示 __debug__
的工作原理,请考虑以下两个函数:
def f():如果 __debug__:返回 3否则:返回 4定义 g():如果为真:返回 3否则:返回 4
现在用dis
检查它们:
如您所见,只有 f
是优化的".
Programming in C
I used to have code sections only used for debugging purposes (logging commands and the like). Those statements could be completely disabled for production by using #ifdef
pre-processor directives, like this:
#ifdef MACRO
controlled text
#endif /* MACRO */
What is the best way to do something similar in python
?
If you just want to disable logging methods, use the logging
module. If the log level is set to exclude, say, debug statements, then logging.debug
will be very close to a no-op (it just checks the log level and returns without interpolating the log string).
If you want to actually remove chunks of code at bytecode compile time conditional on a particular variable, your only option is the rather enigmatic __debug__
global variable. This variable is set to True
unless the -O
flag is passed to Python (or PYTHONOPTIMIZE
is set to something nonempty in the environment).
If __debug__
is used in an if
statement, the if
statement is actually compiled into only the True
branch. This particular optimization is as close to a preprocessor macro as Python ever gets.
Note that, unlike macros, your code must still be syntactically correct in both branches of the if
.
To show how __debug__
works, consider these two functions:
def f():
if __debug__: return 3
else: return 4
def g():
if True: return 3
else: return 4
Now check them out with dis
:
>>> dis.dis(f)
2 0 LOAD_CONST 1 (3)
3 RETURN_VALUE
>>> dis.dis(g)
2 0 LOAD_GLOBAL 0 (True)
3 JUMP_IF_FALSE 5 (to 11)
6 POP_TOP
7 LOAD_CONST 1 (3)
10 RETURN_VALUE
>> 11 POP_TOP
3 12 LOAD_CONST 2 (4)
15 RETURN_VALUE
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
As you can see, only f
is "optimized".
这篇关于你如何实现“#ifdef"?在蟒蛇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!