Python 中的条件编译

发布于 2024-07-13 23:52:02 字数 44 浏览 11 评论 0原文

如何在Python中进行条件编译?

是用 DEF 吗?

How to do conditional compilation in Python ?

Is it using DEF ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

后知后觉 2024-07-20 23:52:02

Python 的编译方式与 C 或 C++ 甚至 Java 不同,Python 文件是“即时”编译的,您可以将其视为类似于 Basic 或 Perl 等解释性语言。1

您可以通过仅使用 if 语句来执行相当于条件编译的操作。 例如:

if FLAG:
    def f():
        print "Flag is set"
else:
    def f():
        print "Flag is not set"

您可以对创建类、设置变量以及几乎所有内容执行相同的操作。

模仿 IFDEF 最接近的方法是使用 hasattr 函数。 例如:

if hasattr(aModule, 'FLAG'):
    # do stuff if FLAG is defined in the current module.

您还可以使用 try/ except 子句来捕获名称错误,但惯用的方法是在脚本顶部将变量设置为 None 。

  1. Python 代码被字节编译成类似于 Java 的中间形式,但通常没有单独的编译步骤。 以 .py 结尾的“原始”源文件是可执行的。

Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.1

You can do something equivalent to conditional compile by just using an if statement. For example:

if FLAG:
    def f():
        print "Flag is set"
else:
    def f():
        print "Flag is not set"

You can do the same for the creation classes, setting of variables and pretty much everything.

The closest way to mimic IFDEF would be to use the hasattr function. E.g.:

if hasattr(aModule, 'FLAG'):
    # do stuff if FLAG is defined in the current module.

You could also use a try/except clause to catch name errors, but the idiomatic way would be to set a variable to None at the top of your script.

  1. Python code is byte compiled into an intermediate form like Java, however there generally isn't a separate compilation step. The "raw" source files that end in .py are executable.
溺孤伤于心 2024-07-20 23:52:02

实际上有一种方法可以获得条件编译,但它非常有限。

if __debug__:
    doSomething()

__debug__ 标志是一种特殊情况。 当使用 -O-OO 选项调用 python 时,__debug__ 将为 false,编译器将忽略该语句。 这主要与断言一起使用,这就是为什么如果您“真正通过优化编译”脚本,断言就会消失。

因此,如果您的目标是添加调试代码,但防止其减慢或以其他方式影响“发布”构建,那么这将满足您的要求。 但是您无法为 __debug__ 赋值,因此这就是您可以使用它的全部用途。

There is actually a way to get conditional compilation, but it's very limited.

if __debug__:
    doSomething()

The __debug__ flag is a special case. When calling python with the -O or -OO options, __debug__ will be false, and the compiler will ignore that statement. This is used primarily with asserts, which is why assertions go away if you 'really compile' your scripts with optimization.

So if your goal is to add debugging code, but prevent it from slowing down or otherwise affecting a 'release' build, this does what you want. But you cannot assign a value to __debug__, so that's about all you can use it for.

℡Ms空城旧梦 2024-07-20 23:52:02

使用 pypreprocessor

也可以在 PYPI(Python 包索引) 并且可以使用 pip 获取。

基本的用法示例是:

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

指定... 将后处理代码输出到文件

pypreprocessor.output = 'output_file_name.py'

您还可以通过在 pypreprocessor 导入和调用 parse() 之间的任意位置

。 该模块本质上是 C 预处理器条件编译的 python 实现。

旁注:这与 python2x 和 python 3k 兼容

免责声明:我是 pypreprocessor 的作者

更新:

我之前忘了提及。 与其他答案中描述的 if/elseif _debug: 方法不同,这是一个真正的预处理器。 生成的字节码将不包含有条件排除的代码。

Use pypreprocessor

Which can also be found on PYPI (Python Package Index) and can be fetched using pip.

The basic example of usage is:

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

You can also output the postprocessed code to a file by specifying...

pypreprocessor.output = 'output_file_name.py'

anywhere between the pypreprocessor import and the call to parse().

The module is essentially the python implementation of C preprocessor conditional compilation.

SideNote: This is compatible with both python2x and python 3k

Disclaimer: I'm the author of pypreprocessor

Update:

I forgot to mention before. Unlike the if/else or if _debug: approaches described in other answers, this is a true preprocessor. The bytecode produced will not contain the code that is conditionally excluded.

梦毁影碎の 2024-07-20 23:52:02

Python 在导入模块时会自动编译模块,因此避免编译模块的唯一方法就是不导入它。 你可以这样写:

if some_condition:
  import some_module

但这只适用于完整的模块。 在 C 和 C++ 中,通常使用预处理器进行条件编译。 没有什么可以阻止您在 Python 代码上使用预处理器,因此您可以编写如下内容:

#ifdef SOME_CONDITION
def some_function():
  pass
#endif

通过 C 预处理器运行该预处理器,您将获得真正的条件编译,并且仅在以下情况下才会定义 some_function code>SOME_CONDITION 已定义。

但是(这很重要):条件编译可能不是您想要的。 请记住,当您导入模块时,Python 只是执行其中的代码。 当您导入模块时,模块中的 def 和 class 语句实际上执行。 因此,实现其他语言使用条件编译的典型方法只是一个普通的 if 语句,例如:

if some_condition:
  def some_function():
    pass

如果 some_condition 为 true,则仅定义 some_function

正是这样的东西使得动态语言如此强大,同时保持概念上的简单。

Python compiles a module automatically when you import it, so the only way to avoid compiling it is to not import it. You can write something like:

if some_condition:
  import some_module

But that would only work for complete modules. In C and C++ you typically use a preprocessor for conditional compilation. There is nothing stopping you from using a preprocessor on your Python code, so you could write something like:

#ifdef SOME_CONDITION
def some_function():
  pass
#endif

Run that through a C preprocessor and you'd have real conditional compilation and some_function will only be defined if SOME_CONDITION is defined.

BUT (and this is important): Conditional compilation is probably not what you want. Remember that when you import a module, Python simply executes the code in it. The def and class statements in the module are actually executed when you import the module. So the typical way of implementing what other languages would use conditional compilation for is just a normal if statement, like:

if some_condition:
  def some_function():
    pass

This will only define some_function if some_condition is true.

It's stuff like this that makes dynamic languages so powerful while remaining conceptually simple.

空心↖ 2024-07-20 23:52:02

在动态环境中没有多大意义。 如果您正在寻找函数的条件定义,可以使用 if

if happy:
    def makemehappy():
        return "I'm good"

Doesn't make much sense in a dynamic environment. If you are looking for conditional definition of functions, you can use if:

if happy:
    def makemehappy():
        return "I'm good"
飘逸的'云 2024-07-20 23:52:02

您可以使用此处讨论的方法:确定变量是否在 Python 中定义 替代 #ifdef

You could use the method discussed here: Determine if variable is defined in Python as a substitute for #ifdef

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文