Try: rather than if :

Cameron Simpson cs at zip.com.au
Mon Dec 14 18:14:20 EST 2015


On 14Dec2015 15:38, Vincent Davis <vincent at vincentdavis.net> wrote:
>In the code below try is used to check if handle has the attribute name. It
>seems an if statement could be used.

Only by using hasattr(), which IIRC does a try/except internally.

>Is there reason one way would be
>better than another?

try/except is more directly, but hasattr() is shorter. However, consider this: 
I would write your example:

>    try:
>        handle.write("# Report_file: %s\n" % handle.name)
>    except AttributeError:
>        pass
>    handle.write("########################################\n")

as:

  try:
    write = handle.write
  except AttributeError:
    pass    # or complain
  else:
    write("# Report_file: %s\n" % handle.name)
    write("########################################\n")

Two things:

First, notice that the code inside the try/except _only_ fetches the attribute.  
Your version calls the "write" attribute, and also accesses handle.name. Either 
of those might also emit AttributeError, and should probably not be silently 
caught.

Second, notice that as a side effect of the:

  write = handle.write

line we now have the attribute value. If it were an if:

  if hasattr(handle, 'write'):
    write = handle.write
    ... write messages now ...

which is two steps to test and get the attribute. Feels... clunky. Perhaps 
partly because of the scope of a spelling error between the "'write'" string 
and the "handle.write" use below it, but clunky anyway.

Which to use depends on how you weigh readability and directness. But try to 
get decide how mugh of your "if" preference is personal uncomfortableness with 
try/except (for whatever reasons), and then how much those reasons may be 
generally applicable or a personal foible.

But it is your code, your call. What reads better to your eye?

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list