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.
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)
The way you're doing it is more-or-less fine. In fact, The python standard library uses a similar paradigm of "try to import something and if it's not valid for some reason then set a variable somehow" in multiple places . Checking if a boolean is set later in the program is going to be faster than doing a separate try/except block every single time.
In your case it would probably just be better to do this, though:
try:
import petsc4py
HAVE_PETSC = True
except ImportError:
HAVE_PETSC = False
What you have works on a paradigm level, but there's no real reason to go through importlib
in this case (and you probably shouldn't use imp
anyway, as it's deprecated in recent versions of python).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.