ahmedfgad / GeneticAlgorithmPython

Source code of PyGAD, a Python 3 library for building the genetic algorithm and training machine learning algorithms (Keras & PyTorch).
https://pygad.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.89k stars 465 forks source link

Throw exception instead of sys.exit in GA.__init__ #213

Closed holasjuraj closed 10 months ago

holasjuraj commented 1 year ago

Use-case:

Minimal example:

def run_ga(**kwargs):
    try:
        ga = pygad.GA(**kwargs)
        ga.run()
        return ga
    except Exception as e:
        my_custom_logger.print(f"GA failed with kwargs = {kwargs} with exception {e}")
        return None

my_ga = run_ga(num_generations=-1)

Desired behavior:

Program runs, and logs an exception with details about the error - i.e. that num_generations has to be positive.

Current implementation:

With the current sys.exit(-1) in GA.__init__, this will not be caught by the except block. Even if we change the except Exception to except SystemExit (which nobody should ever do), then it would log only the SystemExit with no details into my_custom_logger.

Proposed change:

In the GA.__init__, we can replace the end of the function. Instead of the current:

 except Exception as e:
    self.logger.exception(e)
    sys.exit(-1)

We can rather use:

 except Exception as e:
    self.logger.exception(e)
    raise e

This way, the exception will be logged properly into self.logger, but then it will not kill the whole python process, but rather re-raise the exception. The caller of pygad.GA() can then decide whether this exception will be left uncaught and will exit the program, or they will catch it and act upon it.

ahmedfgad commented 10 months ago

Done in a recent commit https://github.com/ahmedfgad/GeneticAlgorithmPython/commit/1615baf463ce428f9c56034c78c5690f34ca9f0a and will be supported in the next release!

holasjuraj commented 10 months ago

Thank you. Closed as resolved.