Coming from a C++ world I got used to write conditional compilation based on flags that are determined at compilation time with tools like CMake and the like. I wonder what's the most Pythonic way to mimic this functionality. For instance, this is what I currently set depending on whether a module is found or not:
import imp
try:
imp.find_module('petsc4py')
HAVE_PETSC=True
except ImportError:
HAVE_PETSC=False
Then I can use HAVE_PETSC
throughout the rest of my Python code. This works, but I wonder if it's the right way to do it in Python.
The if statement is a conditional statement in python, that is used to determine whether a block of code will be executed or not. Meaning if the program finds the condition defined in the if statement to be true, it will go ahead and execute the code block inside the if statement.
If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.
Yes, it is ok. You can even issue an import directly, and use the modulename itself as the flag - like in:
try:
import petsc4py
except ImportError
petsc4py = None
And before any use, just test for the truthfulness of petsc4py
itself.
Actually, checking if it exists, and only then trying to import it, feels unpythonic due to the redundancy, as both actions trigger an ImportError all the same. But having a HAVE_PETSC
variable for the checkings is ok - it can be created after the try/except above with HAVE_PETSC = bool(petsc4py)
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