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.
Use-case:
Minimal example:
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)
inGA.__init__
, this will not be caught by theexcept
block. Even if we change theexcept Exception
toexcept SystemExit
(which nobody should ever do), then it would log only theSystemExit
with no details intomy_custom_logger
.Proposed change:
In the
GA.__init__
, we can replace the end of the function. Instead of the current:We can rather use:
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 ofpygad.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.