Updated 2022-05-21 1
Viewed 5 times
0

I have this code:

def print_trained_network(trained_network):
   print("Accuracy on training set:", trained_network['score_training'])
   print("Accuracy on test set:", trained_network['score_test'])
   print("Execution time", trained_network['time_elapsed'])
   print("Best loss", trained_network['best_loss'])
   print("n_iter", trained_network['n_iter'])
   print("train_shape", trained_network['train_shape'])

   try:
       print("label", trained_network['label'])
   except:
       pass

I want to run every print call in a try except pass, like the last one, without having to add many more lines, by surrounding each with the try catch block.

Is there a way to do it?

🔴 No definitive solution yet
📌 Solution 1
0

I can't think of a "pretty" solution for your problem. But this is a working example of how I would solve that.

trained_network = {
    "one" : "a",
    "two" : "b"
}

def tryPrint(the_str, dic, key):
    try:
        print(the_str + dic[key])
    except:
         print("keyError: " + key)

tryPrint("value: ", trained_network, "one")
tryPrint("value: ", trained_network, "wrong")
tryPrint("value: ", trained_network, "two")

Output:

value: a
keyError: wrong
value: b