Exception problem with module
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed May 14 09:08:28 EDT 2014
On Wed, 14 May 2014 09:21:50 +0000, Joseph L. Casale wrote:
>> I see that you've solved your immediate problem, but you shouldn't call
>> __setattr__ directly. That should actually be written
>>
>> setattr(bar, 'a_new_name', MyError)
>>
>> But really, since bar is (apparently) a module, and it is *bar itself*
>> setting the attribute, the better way is
>>
>> a_new_name = MyError
>>
>> or even
>>
>> from module.foo import MyError as a_new_name
>
> Well I am not sure what advantage this has for the user, not my code as
> I don't advocate the import to begin with it, its fine spelled as it was
> from where it was...
The advantage for the user is:
- it avoids module bar needing to get a reference to itself;
- it avoids the distraction of unnecessarily calling a dunder
method;
- it is idiomatic Python code that should be instantly
understandable by any even moderately experienced
Python coder;
- prevents the reader from puzzling over why the code does
something so unusual ("but why does he do this...?");
- and avoids the inevitable anger and/or contempt when the
reader works out that there is no good reason to write
such unidiomatic code.
One should code as if the next person who reads your program is an easily
upset psychotic axe-murderer who knows where you live. You wouldn't
condone writing y = x.__add__(1) instead of y = x + 1, you shouldn't
condone writing module.__setattr__ directly either.
> I'll look back at this and see if that resolves the
> issue as it had manifested.
I doubt it. Not unless module bar has done something weird, like define a
function called __setattr__ that shadows the actual method and wraps the
exception in another object. More likely, I think you'll find that the
original MyError doesn't inherit from Exception.
--
Steven D'Aprano
http://import-that.dreamwidth.org/
More information about the Python-list
mailing list