user2941525
user2941525

Reputation:

Try/Catch or if?

Is it better to use:

var = "Test"
dictionary = {"test": "test", "test2": "test2"}
try:
    var2 = dictionary[var]

except KeyError:
    pass

or:

var = "test"
if (var == "test" or var == "test2"):
    dosomething()

Which of these is the better way to go? This code is designed to prevent the user from entering a string that is not valid.

Upvotes: 0

Views: 343

Answers (3)

roippi
roippi

Reputation: 25954

Well I'd honestly say neither of those approaches is ideal. The first one uses a dict for a side-effect and is needlessly verbose; the second is very clunky to write and read when there are lots of ors strung together.

I'd recommend using the in operator and a set:

if var in {'test','test2'}:
    #do something

In your first example, you're using a dict as a set stand-in, you should just use a proper set. You want to use a dict when you have an actual mapping of keys to values.

Upvotes: 2

Rushy Panchal
Rushy Panchal

Reputation: 17532

I would go with the try/except mainly because you don't have to explicitly list all of the accepted values. You could just use if var in dictionary.keys(), but why not just a built-in dictionary method?

value = dictionary.get(var) # if it does not find var in the dictionary, returns None
if value is None:
    doSomething()

Of course, this does not work properly when you have a dictionary like such: {var: None}; it would return None regardless of whether or not it can be found in the dictionary. But if you are not expecting any NoneType objects as values, then this is the way to go :).

Upvotes: -1

tomasbedrich
tomasbedrich

Reputation: 1370

If you want the var value to be just one of the set, use this pattern:

var = 'test'
allowed = 'one', 'two', 'three', 'test'

if var in allowed:
    doSomething()
else:
    doSomethingElse()

For the dictionary you can modify the condition like this:

if var in dictionary.keys():

Upvotes: 0

Related Questions