Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you do the equivalent of preprocessor directives in Python?

Is there a way to do the following preprocessor directives in Python?

#if DEBUG  < do some code >  #else  < do some other code >  #endif 
like image 745
intrepion Avatar asked Jan 27 '09 01:01

intrepion


People also ask

Does Python have preprocessor directives?

Since python is an interpreter, there's no preprocessing step to be applied, and no particular advantage to having a special syntax. Being an interpreter doesn't have anything to do with it.

What are directives in Python?

A directive statement instructs the Python interpreter to process a source file in a different way; the specific details of that processing depend on the directive name. The optional atom is typically interpreted when the source code is processed; details of that interpretation depend on the directive.

Is there #define in Python?

Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword.

How do you write a preprocessor directive?

Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include extra code in your program.


1 Answers

There's __debug__, which is a special value that the compiler does preprocess.

if __debug__:   print "If this prints, you're not running python -O." else:   print "If this prints, you are running python -O!" 

__debug__ will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove any if 0: lines before your source is interpreted.

like image 193
habnabit Avatar answered Sep 28 '22 21:09

habnabit