'How to replace error with a value in python [closed]

I am using AutoSklearn library in this library, there is a function called leaderboard()

sometimes this function gives error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/my/anaconda3/lib/python3.8/site-packages/autosklearn/estimators.py", line 841, in leaderboard
    model_runs[model_id]['ensemble_weight'] = weight
KeyError: 1

I am using this function as part of a string

out = out + "automl.leaderboard() : " + automl.leaderboard() + "\n\r"

I want to replace the error with a string value "Error"

how can I do that?

P.S. Here is the bug description for the error from the library github.

https://github.com/automl/auto-sklearn/issues/1441



Solution 1:[1]

You can use a try / except block. Something like this:

try:
    out = out + "automl.leaderboard() : " + automl.leaderboard() + "\n\r"
except KeyError as err:
    out = out + "automl.leaderboard() : " + str(err) + "\n\r"

Solution 2:[2]

Use try/except to try to get the leaderboard value, substituting "Error" when KeyError is raised:

try:
    leaderboard = automl.leaderboard()
except KeyError:
    leaderboard = "Error"
out += f"automl.leaderboard() : {leaderboard}\n\r"

Solution 3:[3]

You can use a try/except block to do this.

try:
    leaderboard = automl.leaderboard()
except KeyError:
    leaderboard = "Error"  # If there is an error, leaderboard will be set to "Error"
out = out + "automl.leaderboard() : " + leaderboard + "\n\r"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Valentino
Solution 2 Samwise
Solution 3 wolf