Try: rather than if :

Cameron Simpson cs at zip.com.au
Tue Dec 15 01:11:19 EST 2015


On 14Dec2015 16:48, Vincent Davis <vincent at vincentdavis.net> wrote:
>On Mon, Dec 14, 2015 at 4:14 PM, Cameron Simpson <cs at zip.com.au> wrote:
>
>> 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.
>>
>
>​I think the intent of the original code was to check if handle had the
>attribute "name", I don't think the attribute "write" was the issue.

I have to say that this was not at all evident to me. I think that also argues 
for putting the smallest possible bit of code inside the try/except.

>So then possibly this based on your suggestion:
>try:
>    write = handel.write
>except AttributeError:
>    raise

Someone has already suggested dropping the try/except altogether for this.

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

Again, I would minimise the stuff in the try/except, so:

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

But in this case, in my code, I do two things:

Firstly, things needing names always get one:

  class Foo:
    def __init__(self, blah, name=None):
      if name is None:
        name = "Foo-%s" % (id(self),)
      self.name = name

Secondly, for your use case "print the name if it has one" I _would_ use 
hasattr:

  if hasattr(handle, name):
    write("# Report_file: %s\n" % name)

The logic feels far clearer to my eye.

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



More information about the Python-list mailing list