Method Call in Exception
Kent Johnson
kent at kentsjohnson.com
Thu Apr 20 09:46:53 EDT 2006
Carl Banks wrote:
> mwt wrote:
>> In my latest attempt at some Python code, I've been tempted to write
>> something in the form of:
>>
>> try:
>> [...] #doing some internet stuff
>> except IOError:
>> alternate_method_that_doesnt_need_internet()
>>
>> This works when I try it, but I feel vaguely uneasy about putting
>> method calls in exception blocks. So tell me, Brave Pythoneers, is this
>> evil sorcery that I will end up regretting, or is it just plain good
>> ol' Python magic?
>
> It's ok. In fact a lot of Pythonistas recommend this way over the
> alternative, even when you don't have to. For example, a lot of people
> recommend this:
>
> try:
> name = record.name
> except AttributeError:
> name = "Freddy"
>
> instead of this:
>
> if hasattr(record,"name"):
> name = record.name
> else:
> name = "Freddy"
or maybe
name = getattr(record, 'name', 'Freddy')
Kent
More information about the Python-list
mailing list