简体   繁体   English

什么是Pythonic基于已安装的模块编写条件语句的方法?

[英]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. 来自C ++世界,我习惯于使用像CMake之类的工具在编译时确定的标志来编写条件编译。 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. 然后我可以在我的其余Python代码中使用HAVE_PETSC This works, but I wonder if it's the right way to do it in Python. 这有效,但我想知道它是否是在Python中使用它的正确方法。

Yes, it is ok. 是的,没关系。 You can even issue an import directly, and use the modulename itself as the flag - like in: 您甚至可以直接发出导入,并使用modulename本身作为标志 - 如:

try:
    import petsc4py
except ImportError
    petsc4py = None

And before any use, just test for the truthfulness of petsc4py itself. 在任何使用之前,只需测试petsc4py本身的真实性。

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. 实际上,检查它是否存在,然后只是尝试导入它,由于冗余而感觉是unpythonic,因为两个动作都会触发ImportError。 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) 但是检查有一个HAVE_PETSC变量是可以的 - 它可以在上面的try / except之后使用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 . 实际上,python标准库使用了一种类似的范例:“尝试导入一些东西,如果由于某种原因它无效,那么 多个 地方设置一个变量”。 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. 检查程序中稍后是否设置了布尔值将比每次执行单独的try / except块更快。

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). 你在范例层面上有什么工作,但在这种情况下没有真正的理由通过importlib (你可能不应该使用imp ,因为它在最近的python版本中已被弃用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM