Handling NameError in a list gracefully

Terry Reedy tjreedy at udel.edu
Mon Apr 20 20:26:50 EDT 2009


Jesse Aldridge 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?

I would consider giving my_paths a 'selected_paths' attribute that you 
update by hand or automatically within my_paths.




More information about the Python-list mailing list