I want to do something like this in C:
#ifdef SOMETHING
do_this();
#endif
But in Python this doesn't jive:
if something:
import module
What am I doing wrong? Is this possible in the first place?
I want to do something like this in C:
#ifdef SOMETHING
do_this();
#endif
But in Python this doesn't jive:
if something:
import module
What am I doing wrong? Is this possible in the first place?
It should work fine:
>>> 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)>
In Python there's a built-in feature called "Exception".. Applying to your needs:
try:
import <module>
except: #Catches every error
raise #and print error
There are more complex structures so search on the web for more documentation.
If you're getting this:
NameError: name 'something' is not defined
then the problem here is not with the import
statement but with the use of something
, a variable you apparently haven't initialized. Just make sure it's initialized to either True or False, and it'll work.
In the C construct, the conditional define #ifdef tests whether "SOMETHING" exists only, where your python expression tests whether the value of the expression is either True or False, in my opinion two very different things, in addition, the C construct is evaluated at compile time.
"something" based in your original question must be a variable or expression that (exists and) evaluates to true or false, as other people already pointed out, the problem may be with that "something" variable not being defined. so the "closest equivalent" in python would be something like:
if 'something' in locals(): # or you can use globals(), depends on your context
import module
or (hacky):
try:
something
import module
except NameError, ImportError:
pass # or add code to handle the exception
hth