about 'setattr(o, name, value)' and 'inspect.signature(f)'

Steve D'Aprano steve+python at pearwood.info
Tue Oct 10 20:59:58 EDT 2017


On Wed, 11 Oct 2017 02:15 am, Paul Moore wrote:

> These are all run-time behaviours, and so there's no way you can check
> for them ahead of time. If you want to be sure setattr is allowed, you
> need to handle possible exceptions:
> 
>     try:
>         setattr(o, name, value)
>     except Exception:
>         # deal with the problem


I would say that you should only catch AttributeError here. Anything else is,
in my opinion, a bug in the object o that needs to be spotted and fixed.

Even catching AttributeError is a bit... suspicious. Why exactly are we trying
to attach attributes to arbitrary objects like None or "Hello World"?

But certainly if you get something like UnicodeDecodeError or ImportError from
trying to set an attribute, that's a bug in o.__setattr__ that needs fixing.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list