flakes
flakes

Reputation: 23664

How to properly handle variables if an exception is thrown?

This might be more of an opinion based question, but I'll continue anyway!

I have many functions that get multiple values from remote devices and I need to use the most up to date values when I do my calculations. Being that its a remote device, I have to use device specific getters when asking for the values.

(I'm using the telnetlib, but I assume that's irrelevant)

In actual use, it's safe to assume I'll have around 10+ devices, and 10+ values to get from each. There is a chance that the communication with the device will fail and raise an exception. In this case all the data I collected will be useless seeing as I need all of it do my calculations, and I shouldn't save it because it wont be the most up to date values later.

So far my functions looks like this... the main idea being that if any of the getters fail, the append lines will not be executed:

def GetTraits(object_list):
    trait_dict = {"Foo":[],"Bar":[]}
    for obj in object_list:
        try:
            Foo = obj.GetFoo()
            Bar = obj.GetBar()
            trait_dict["Foo"].append(Foo)
            trait_dict["Bar"].append(Bar)
        except Exception as e:
            print e
            # None type will be handled by other functions that need these values
            trait_dict["Foo"].append(None)
            trait_dict["Bar"].append(None)
    return trait_dict

This however feels like a lot of very redundant code seeing as I could have 10+ traits in that dictionary.

Any ideas on how to improve this code? Thanks in advance!

Cal

Upvotes: 0

Views: 35

Answers (1)

loopbackbee
loopbackbee

Reputation: 23332

Types, classes and methods (and class methods) are all first-class objects in python. A simple way of doing it is to simply treat methods as objects:

#...
trait_names= ("trait1", "trait2")
gets= (obj.GetTrait1, obj.GetTrait2())

try:
    for trait,get in zip(trait_names, gets):
        trait_dict[trait]=get()
except:
    for trait,get in zip(trait_names, gets):
        trait_dict[trait]=None

If you have a consistent naming scheme, you may want to generate the method names using string manipulation and get them using getattr.

t= "Trait1"
getter= getattr( obj, "Get"+t )

Upvotes: 1

Related Questions