简体   繁体   中英

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.

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 or s 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.

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():

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 :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM