Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #100447

Re: Try: rather than if :

From Cameron Simpson <cs@zip.com.au>
Newsgroups comp.lang.python
Subject Re: Try: rather than if :
Date 2015-12-15 17:11 +1100
Message-ID <mailman.11.1450159883.22044.python-list@python.org> (permalink)
References <CALyJZZWn-UJPkMtNOBX9YcvAmWgA4qTo7_LwhHjciwevmrn1xw@mail.gmail.com>

Show all headers | View raw


On 14Dec2015 16:48, Vincent Davis <vincent@vincentdavis.net> wrote:
>On Mon, Dec 14, 2015 at 4:14 PM, Cameron Simpson <cs@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@zip.com.au>

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Try: rather than if : Cameron Simpson <cs@zip.com.au> - 2015-12-15 17:11 +1100

csiph-web