hasattr() or "x in y"?

Grant Edwards invalid at invalid.invalid
Fri Mar 11 17:30:46 EST 2016


On 2016-03-11, Charles T. Smith <cts.private.yahoo at gmail.com> wrote:
> On Fri, 11 Mar 2016 22:00:41 +0000, Grant Edwards wrote:
>
>> Since they behave differently, perhaps the question ought to be "which
>> does what you want to do?"
>
> For parsed msgs, I had this:
>
>               elif hasattr (msg.msgBody, 'request'):
>
> It occurred to me that this was less abstruse:
>
>               elif 'request' in msg.msgBody:

If you want to know if msg.msgBody has an attribute named 'request'
then use hasattr().

If you want to know if msg.msgBody "contains"[1] the string 'request'
then use "in".

_They're_two_different_things_

[1] for some definition of "contains" that depends on the type of
msg.msgBody.

> and by the way, how would you do that with duck-typing?

Do WHAT?

> If I were doing this anew, I probably use a dictionary of functors,
> but that's not an option anymore.

-- 
Grant Edwards               grant.b.edwards        Yow! Were these parsnips
                                  at               CORRECTLY MARINATED in
                              gmail.com            TACO SAUCE?



More information about the Python-list mailing list