Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Pythonic way to write conditional statements based on installed modules?

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.

like image 853
aaragon Avatar asked Aug 05 '19 15:08

aaragon


People also ask

What are conditional statements which conditional statements are provided by 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.

Which keyword is used for writing multiple conditional statements in Python?

If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.


1 Answers

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)

like image 62
jsbueno Avatar answered Oct 12 '22 00:10

jsbueno