An example of a subtle over-broad
try in Python
Today I wrote some code to winnow a list of users to 'real' users with live home directories that looks roughly like the following:
for uname, hdir in userlist: try: st = os.stat(hdir) if not stat.S_ISDIR(st.st_mode) or \ stat.S_IMODE(st.st_mode) == 0: continue # looks good: print uname except EnvironmentError: # accept missing homedir; might be a # temporarily missing NFS mount, we # can't tell. print uname
This code has a relatively subtle flaw because I've accidentally written an over-broad exception catcher here.
As suggested by the comment, when I wrote this code I intended the
try block to catch the case where the
os.stat failed. The flaw
here is that
try block, a
except will re-do the
except case then becomes just '
(My view is that
try block and then do something if it failed, or have
try block around the entire operation to catch otherwise
The root cause here is that I wasn't thinking of
try blocks to only
things that absolutely have to be there, as opposed to things that are
just kind of convenient for the flow of code.
As a side note, one of the things that led to this particular case
is that I changed my mind about what should happen when the
failed because I realized that failure might have legitimate causes
instead of being a sign of significant problems with an account
that should cause it to be skipped. When I changed my mind I just
did a quick change to what the
except block did instead of totally
revising the overall code, partly because this is a small quick
program instead of a big system.
Comments on this page:Written on 18 August 2014.