Ricardo Aráoz wrote:
> Paul McNett wrote:
>> Ricardo Aráoz wrote:
>>> Paul McNett wrote:
>>>> Actually, you'd be better off checking that you have an object first:
>>>>
>>>> lbl = getattr(self, curlabel, None)
>>>> if lbl:
>>>> lbl.Caption = "somestr"
>>>>
>>>> HTH
>>>>
>>> How un-pythonic! Use exceptions!
>> Ok:
>>
>> try:
>> lbl = getattr(self, curlabel)
>> except AttributeError:
>> lbl = None
>>
>> if lbl:
>> lbl.Caption = "somestr"
>>
>> Please explain why those 6 lines are better than my original 3.
>>
>
> try : lbl = getattr(self, curlabel)
> except: # do other stuff your original code won't do
Well, actually, I could have added an else: if I needed that...
> finally : lbl.Caption = "somestr"
>
> I guess those three lines do what your original 3 do, but faster.
Faster? In this case, I believe it would tie. Exceptions when raised are
not good performance-wise. However, I believe that the getattr() call
will cause an AttributeError if the attribute doesn't exist (which it
catches and snuffs out if you provide a default value, or re-raises if
not). So exceptions are being raised in either case, resulting in a tie
performance-wise.
But, we shouldn't really be talking about performance, unless it is
demonstratively a bottleneck. Using try blocks is highly encouraged in
Python, as they add to readability and self-documentation. However, I
don't think it is unpythonic to have exceptions to the rule if I think
the code is more readable or sensible with a 'look-before-you-leap'
approach.
> Or if you accept an Xtra line :
>
> try :
> lbl = getattr(self, curlabel)
> lbl.Caption = "somestr"
> except : pass # or some other line with xtra functionality
I truly thought you'd come back with a better counter, one that is more
pythonic in the 'it is easier to ask forgiveness than permission'
mantra. :) However, I guess in this context that isn't possible given
the constraint that we don't know the name of the attribute. Normally,
I'd do something like:
try:
o = self.obj1
o.Caption = ...
except AttributeError:
pass
But that just wasn't possible this time, and I thought getattr(obj, attr
, default) was every bit as readable as wrapping it in a try block, in
this case.
> BTW didn't mean to pick a fight, though re-reading my post you might
> have interpreted it that way, sorry if that was the case.
Not offended at all! :)
--
pkm ~ http://paulmcnett.com
_______________________________________________
Post Messages to: [email protected]
Subscription Maintenance: http://leafe.com/mailman/listinfo/dabo-users
Searchable Archives: http://leafe.com/archives/search/dabo-users
This message: http://leafe.com/archives/byMID/dabo-users/[EMAIL PROTECTED]