Alex Rivera | Logout

Conditional compilation in Python

Asked 2009-02-18T06:26:54.260
19

How to do conditional compilation in Python ?

Is it using DEF ?

Edit
Report

1 Answer

20

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.

answered 2011-03-16T02:53:03.407

Your Answer