简体   繁体   English

Python 模块不总是可用时的最佳实践

[英]Python best practice for when an module is not always available

I have a Python code that runs on cuda.我有一个在 cuda 上运行的 Python 代码。 Now I need to support new deployment devices that cannot run cuda because they don't have Nvidia GPUs.现在我需要支持无法运行 cuda 的新部署设备,因为它们没有 Nvidia GPU。 Since I have many cupy imports in the code, I am wondering what is the best practice for this situation.由于我在代码中有很多cupy导入,我想知道这种情况的最佳实践是什么。

For instance, I might have to import certain classes based on the availability of cuda.例如,我可能必须根据 cuda 的可用性导入某些类。 This seems nasty.这看起来很恶心。 Is there any good programming pattern I can follow?我可以遵循任何好的编程模式吗?

For instance, I would end up doing something like this:例如,我最终会做这样的事情:

from my_custom_autoinit import is_cupy_available
if is_cupy_available:
    import my_module_that_uses_cupy

where my_custom_autoinit.py is:其中my_custom_autoinit.py是:

try:
    import cupy as cp
    is_cupy_available = True
except ModuleNotFoundError:
    is_cupy_available = False

This comes with a nasty drawback: every time I want to use my_module_that_uses_cupy I need to check if cupy is available.这带来了一个令人讨厌的缺点:每次我想使用my_module_that_uses_cupy时,我都需要检查cupy是否可用。 I don't personally like this and I guess somebody came up with something better than this.我个人不喜欢这个,我猜有人想出了比这更好的东西。 Thank you谢谢

You could add a module called cupywrapper to your project, containing your try..except您可以在项目中添加一个名为cupywrapper的模块,其中包含您的try..except

cupywrapper.py Cupywrapper.py

try:
    import cupy as cp
    is_cupy_available = True
except ModuleNotFoundError:
    import numpy as cp
    is_cupy_available = False

I'm assuming you can substitute cupy with numpy because from the website :我假设您可以用numpy代替cupy ,因为来自网站

CuPy's interface is highly compatible with NumPy; CuPy的接口与NumPy高度兼容; in most cases it can be used as a drop-in replacement.在大多数情况下,它可以用作替代品。 All you need to do is just replace numpy with cupy in your Python code.您只需在 Python 代码中用 cupy 替换 numpy 即可。

Then, in your code, you'd do:然后,在您的代码中,您将执行以下操作:

import cupywrapper
cp = cupywrapper.cp

# Now cp is either cupy or numpy
x = [1, 2, 3]
y = [4, 5, 6]
z = cp.dot(x, y)

print(z)
print("cupy? ", cupywrapper.is_cupy_available)

On my computer, I don't have cupy installed and this falls back to numpy.dot , giving an output of在我的电脑上,我没有安装cupy ,这回落到numpy.dot ,给出 output

32
cupy? False

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

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