python-2.7largenumbergmpy

Define a function based on available modules


I have a function I need to calculate which has to work with fairly large numbers (something like 200^200). I found i can deal with it fairly well using the Decimal package, however the function is quite slow. I therefore installed the GMPY2 package, and was able to cut down the time by about seventh. However I need to distribute the function to others, and not everyone has the GMPY2 module. How can I change the definition of the function based on the available modules. Can I do something like this:

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

or will it cause problems? Is there a better way


Solution

  • That will work but i'd do something along the lines of

    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
    

    This way makes it cleaner and more manageable