Conditional compilation in Python

How to do conditional compilation in Python ?

Is it using DEF ?


Asked by: Julian665 | Posted: 06-12-2021






Answer 1

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.

  1. Python code is byte compiled into an intermediate form like Java, however there generally isn't a separate compilation step. The "raw" source files that end in .py are executable.

Answered by: Wilson407 | Posted: 07-01-2022



Answer 2

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.

Answered by: Cherry111 | Posted: 07-01-2022



Answer 3

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 by: Alissa320 | Posted: 07-01-2022



Answer 4

Python compiles a module automatically when you import it, so the only way to avoid compiling it is to not import it. You can write something like:

if some_condition:
  import some_module

But that would only work for complete modules. In C and C++ you typically use a preprocessor for conditional compilation. There is nothing stopping you from using a preprocessor on your Python code, so you could write something like:

#ifdef SOME_CONDITION
def some_function():
  pass
#endif

Run that through a C preprocessor and you'd have real conditional compilation and some_function will only be defined if SOME_CONDITION is defined.

BUT (and this is important): Conditional compilation is probably not what you want. Remember that when you import a module, Python simply executes the code in it. The def and class statements in the module are actually executed when you import the module. So the typical way of implementing what other languages would use conditional compilation for is just a normal if statement, like:

if some_condition:
  def some_function():
    pass

This will only define some_function if some_condition is true.

It's stuff like this that makes dynamic languages so powerful while remaining conceptually simple.

Answered by: Jared773 | Posted: 07-01-2022



Answer 5

Doesn't make much sense in a dynamic environment. If you are looking for conditional definition of functions, you can use if:

if happy:
    def makemehappy():
        return "I'm good"

Answered by: Freddie334 | Posted: 07-01-2022



Answer 6

You could use the method discussed here: Determine if variable is defined in Python as a substitute for #ifdef

Answered by: Emma967 | Posted: 07-01-2022



Similar questions

conditional - "Pythonic" equivalent for handling switch and multiple string compares

Alright, so my title sucked. An example works better: input = 'check yahoo.com' I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it: if len(input) > 0: a = input.split(' ') if a[0] == 'check': if len(a) > 1: do_check(a[1...


python - Django way to do conditional formatting

What is the correct way to do conditional formatting in Django? I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want green and ones after I want red. Somewhere in Django you will need to do that comparison, c...


arrays - Conditional counting in Python

not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have class A: def __init__(self, a, b): self.a = a self.b = b stuff = [] for i in range(1,10): stuff.append(A(i/2, i%2)) Now I would like...


python - How to do conditional character replacement within a string

I have a unicode string in Python and basically need to go through, character by character and replace certain ones based on a list of rules. One such rule is that a is changed to ö if a is after n. Also, if there are two vowel characters in a row, they get replaced by one vowel character and :. So if I have the string "natarook", what is the eas...


indexing - How does the Python conditional operator workaround work?

From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.). I found the following code as a substitute: def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var>65] print "You should be:",status I couldn't understand how this code works; can anyone explain me how actually the code is wor...


if statement - conditional skip in python if

i am trying for something like this def scanthefile(): x = 11 if x > 5 """ i want to come out of if and go to end of scanfile """ print x return info update: if have to check for the content size of a file. and if the content size is larger than a value say 500 , then i should go to the end of the scanfile


python - Does Ruby support conditional regular expressions

Just a language feature question, I know there's plenty of ways to do this outside of regexes (or with multiple regexes). Does ruby support conditional regular expressions? Basically, an IF-THEN-ELSE branch inside a regular expression, where the predicate for the IF is the presence (or absense) of a...


syntax - Conditional operator in Python?

This question already has answers here:


python - How to improve the speed of a loop containing a sqlalchemy query statement as conditional

This loop checks if a record is in the sqlite database and builds a list of dictionaries for those records that are missing and then executes a multiple insert statement with the list. This works but it is very slow (at least i think it is slow) as it takes 5 minutes to loop over 3500 queries. I am a complete newbie in python, sqlite and sqlalchemy so I wonder if there is a faster way of doing this. list_di...


python - Conditional Regular Expressions

I'm using Python and I want to use regular expressions to check if something "is part of an include list" but "is not part of an exclude list". My include list is represented by a regex, for example: And.* Everything which starts with And. Also the exclude list is represented by a regex, for example: (?!Andrea) Ev...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top