How to do conditional compilation in Python ?
Is it using DEF ?
Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.
The $ELSE statement is used in conjunction with the $IF statement to control conditional compilation. The $END statement is used in conjunction with the $IF statement to control conditional compilation. A $IF statement provides the means whereby selected parts of the source text are not included in the compilation.
The conditional compilation practice is used to optionally remove chunks of code from the compiled version of a class. It uses the fact that compilers will ignore any unreachable branches of code. To implement conditional compilation, define a static final boolean value as a non-private member of some class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With