1

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

Nicolo Castro
  • 195
  • 1
  • 3
  • 8

1 Answers1

1

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

Reidon
  • 46
  • 4
  • Thank you, I'll do that then. I had thought about it as I do something similar elsewhere, I just wasn't sure how clear the code would be by placing both definitions within the same def statement. – Nicolo Castro Jun 30 '17 at 08:34