Try: rather than if :

jmp jeanmichel at sequans.com
Tue Dec 15 07:19:20 EST 2015


On 12/14/2015 11:38 PM, Vincent Davis wrote:
> In the code below try is used to check if handle has the attribute name. It
> seems an if statement could be used. Is there reason one way would be
> better than another?
>
> def write_header(self):
>      handle = self.handle
>      try:
>          handle.write("# Report_file: %s\n" % handle.name)
>      except AttributeError:
>          pass
>      handle.write("########################################\n")
>
> The specific use case I noticed this was
> https://github.com/biopython/biopython/blob/master/Bio/AlignIO/EmbossIO.py#L38
>
> Vincent Davis
>

Nothing wrong with the try block. However other forms may be 
shorter/more readable.
Since there is 2 attribute lookups in the try block, (write and name) 
it's not clear which one you want to catch (except for the line 
following the except clause but it could not be the case).

Here are 2 alternative forms

1/ handle.write(handle.name if hasattr(handle, 'name') else '')
2/ handle.write(getattr(handle, 'name', ''))

Here's the best solution imo:
3/ assume handle has always a name attribute and don't write code 
handling attribute existence. Instead handle the attribute values:

class Handle:
   def __init__(self):
     self.name= None # and the problem is gone

if handle.name : handle.write(handle.name)


By the way, in the use case you've linked, it is written
'handle = self.handle'
at every beginning of each method. Don't follow that rule.


Jm





More information about the Python-list mailing list