2

我想在 C 中做这样的事情:

#ifdef SOMETHING
do_this();
#endif

但在 Python 中,这并不能解决问题:

if something:
    import module

我究竟做错了什么?首先这可能吗?

4

4 回答 4

18

它应该可以正常工作:

>>> if False:
...     import sys
... 
>>> sys
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> if True:
...     import sys
... 
>>> sys
<module 'sys' (built-in)>
于 2009-12-04T10:42:34.573 回答
1

如果你得到这个:

NameError: name 'something' is not defined

那么这里的问题不在于import语句,而在于使用something显然尚未初始化的变量。只要确保它被初始化为 True 或 False,它就会工作。

于 2009-12-04T14:36:55.957 回答
1

在C构造中,条件定义#ifdef测试是否仅存在“SOMETHING”,您的python表达式测试表达式的是True还是False,在我看来是两个非常不同的东西,此外,C构造是在编译时评估。

正如其他人已经指出的那样,基于您原始问题的“某事”必须是一个(存在并且)评估为真或假的变量或表达式,问题可能在于未定义该“某事”变量。所以python中的“最接近的等价物”是这样的:

if 'something' in locals(): # or you can use globals(), depends on your context
    import module

或(hacky):

try:
    something
    import module
except NameError, ImportError:
    pass # or add code to handle the exception

hth

于 2009-12-04T22:01:54.717 回答
1

在 Python 中有一个名为“异常”的内置功能。适用于您的需求:

try:

    import <module>

except:     #Catches every error
    raise   #and print error

有更复杂的结构,因此请在网络上搜索更多文档。

于 2009-12-04T14:31:50.053 回答