Handling NameError in a list gracefully

Chris Rebert clp2 at rebertia.com
Mon Apr 20 22:46:35 CEST 2009

On Mon, Apr 20, 2009 at 1:36 PM, Jesse Aldridge <JesseAldridge at gmail.com> wrote:
> from my_paths import *
> def get_selected_paths():
>    return [home, desktop, project1, project2]
> -------
> So I have a function like this which returns a list containing a bunch
> of variables.  The real list has around 50 entries.  Occasionally I'll
> remove a variable from my_paths and cause get_selected_paths to throw
> a NameError.  For example, say I delete the "project1" variable from
> my_paths; now I'll get a NameError when I call get_selected_paths.
> So everything that depends on the get_selected_paths function is
> crashing.  I am wondering if there is an easy way to just ignore the
> variable if it's not found.  So, in the example case I would want to
> somehow handle the exception in a way that I end up returning just
> [home, desktop, project2].
> Yes, I realize there are a number of ways to reimplement this, but I'm
> wanting to get it working with minimal changes to the code.  Any
> suggestions?

def get_selected_paths():
    variables = "home desktop project1 project2".split()
    vals = []
    for var in variables:
            vals.append(getattr(my_paths, var))
        except AttributeError:
    return vals

I have a blog:

More information about the Python-list mailing list