mattsun mattsun - 22 days ago 7
Python Question

Selective compilation

I'm wondering is there a capability, in any programming language, that I can choose to compile only a certain part of code. See example below.

This is a block of pseudocode:

function foo() {

if (isDebug) {
checkSomethingForDebugging();
print(some debug info);
}

toSomeFooThings();
}


This block is for debugging purpose, I want to ignore them (even the if statement) in production.

if (isDebug) {
checkSomethingForDebugging();
print(some debug info);
}


One thing I can do is to comment out these lines,

function foo() {

//if (isDebug) {
// checkSomethingForDebugging();
// print(some debug info);
//}

toSomeFooThings();
}


But what if I have thousands of places like this? It will be good if there is a way (a flag) that I can choose to compile a certain part of the code or not. It's like a
debugging build
. Is there anything for this in any programming language? I did search online but was no luck.

Answer

Most languages don't have this, but you could certainly write a script which processed the source code somewhere in your build/deploy pipeline and deleted the debug only parts. An advanced way would be to properly parse the source code and delete the appropriate if blocks. For Python this would be quite easy using either the ast module or just looking for lines saying if is_debug: and then watching the indentation level. For other languages it might be harder. A simpler way in terms of the preprocessing script would be to use delimiting comments:

// DEBUGONLY
checkSomethingForDebugging();
print(some debug info);
// ENDDEBUGONLY

In this case the if statement is optional depending on how exactly you want to do things.

Comments