根据可用模块定义函数

Define a function based on available modules

我有一个函数需要计算,它必须处理相当大的数字(比如 200^200)。我发现我可以使用 Decimal 包很好地处理它,但是这个函数很慢。因此我安装了 GMPY2 包,并且能够将时间减少大约七分之一。但是我需要把功能分发给其他人,并不是每个人都有GMPY2模块。如何根据可用模块更改函数的定义。我可以这样做吗:

try:
    import gmpy2
    def function_with_big_numbers()
exceptImportError:
    import decimal
    def function_with_big_numbers()

还是会出问题?有没有更好的方法

那会起作用,但我会按照

做一些事情
try:
    import gmpy2
except:
    gmpy2 = None

def function_with_big_numbers():
    if gmpy2 is None:
        # put code executed when gpy2 is not available
        return
    # put code executed when gpy2 is available

这种方式使它更干净、更易于管理