2

Sorry for the multiple posts, and I did look around and couldn't find anything besides the try method, which seems useful in some situations, just not mine.

What I'm looking for is a way to kind of skip errors, so just no display in the console and not stopping of the script, just a way to bypass them.

ie;

1. call a list
2. If list does not exist
3.     create the list
GoodPie
  • 967
  • 3
  • 23
  • 41

2 Answers2

5

In Python this is acheived with try...except. In your case, you probably want to catch NameError.

try:
    L[0]
except NameError:
    L = ["Example",2]
    L[0]
Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61
  • ahhh... thankyou, i was looking at the try and someone stated that it could only be used if raising the same exception or something, so i thought it didn't work, my bad :c – GoodPie Jan 06 '13 at 17:00
1

try .. except is certainly one way to go. If you are trying to test arguments within a function, then it is often useful to define this argument with the default value None and test like this:

def myfunc(..., mylist=None):
    if mylist is None:
        mylist = []

(see also not None test in Python)

If you want to find out if the list is empty, just type

if mylist:
    print mylist
else:
    print "empty list"

The key difference between these types of tests and the try .. except concept is that in my code examples you must be sure that the variable is defined (for example as a function argument). Otherwise you will generate an Exception. And this is precisely what the try .. except construct handles graciously.

In the end it may be philosophical (and I can only hope that I don't violate the zen of python with this): If you know which variables may be undefined, it can improve the readability and resilience of your code if you code the error handling explicitly. Some might say it is more pythonic to "let it happen" and fix only where necessary. If you are writing a "quick hack", solution 2 is often fine, if it is an application that other users are supposed to use, I usually favour explicit error handling.

Community
  • 1
  • 1
maschu
  • 1,355
  • 1
  • 18
  • 33